Jump to content

  • Log In with Google      Sign In   
  • Create Account

Executing a function stored as a variable


Old topic!
Guest, the last post of this topic is over 60 days old and at this point you may not reply in this topic. If you wish to continue this conversation start a new topic.

  • You cannot reply to this topic
3 replies to this topic

#1 Dragon88   Members   -  Reputation: 246

Like
Likes
Like

Posted 03 May 2003 - 02:14 PM

I''m making a scripting language that is somewhat similar to Lua, and I''m trying to figure out how to register and execute functions, like Lua does. In Lua, when you want a script to be able to recognize a function that is defined in your program you call lua_register() and it places the function you pass into a variable. I''ve figured out how to do that, my question is, how do I call that function? Below is a (very) simplified representation of how I am implementing all this.
  
typedef int (*CFunction)();
CFunction theFunction;

void RegisterFunc(gsFunc f)
{
   theFunction = f;
}
void DoSomething()
{
   int temp = theFunction();
}
int TheRealFunc()
{
   a=a+1;
}
int main()
{
   RegisterFunc(TheRealFunc());
   DoSomething();
   return 0;
}
  
All this compiles, but when I run it it commits and Illegal Op. Why, and how can I fix it?
(Stolen from Programmer One) UNIX is an operating system, OS/2 is half an operating system, Windows is a shell, and DOS is a boot partition virus

Sponsor:

#2 Rian   Members   -  Reputation: 121

Like
Likes
Like

Posted 03 May 2003 - 02:27 PM

When you pass TheRealFunc to RegesterFunc, you want to pass it as a pointer, not the return value of the function. You need to change it to RegisterFunc(TheRealFunc); instead of registerFunc(TheRealFunc());.

ex:
int Function() { return 100; }
int a = Function(); //a = 100;
CFunction b = Function; //CFunction now points to Function();
void PassFunc(CFunction func) { }
PassFunc(Function()); //attemps to pass 100 as a CFunction (error)
PassFunc(Function); //passes a pointer to Function as a CFunction (works)





[edited by - Rian on May 3, 2003 9:34:22 PM]

#3 Dragon88   Members   -  Reputation: 246

Like
Likes
Like

Posted 03 May 2003 - 02:29 PM

Ahhh. I''ll try that. Thanks.




(Stolen from Programmer One)
UNIX is an operating system, OS/2 is half an operating system, Windows is a shell, and DOS is a boot partition virus

#4 Rian   Members   -  Reputation: 121

Like
Likes
Like

Posted 03 May 2003 - 02:36 PM

glad I could help.




Old topic!
Guest, the last post of this topic is over 60 days old and at this point you may not reply in this topic. If you wish to continue this conversation start a new topic.



PARTNERS