Archived

This topic is now archived and is closed to further replies.

Dragon88

Executing a function stored as a variable

Recommended Posts

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

Share this post


Link to post
Share on other sites
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]

Share this post


Link to post
Share on other sites
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

Share this post


Link to post
Share on other sites