Executing a function stored as a variable

Started by
2 comments, last by Dragon88 20 years, 11 months ago
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
Advertisement
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]
I can imagine a world without hate, a world without fear, a world without war. And I can imagine us attacking that world, because they would never expect it. -Jack Handy
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
glad I could help.
I can imagine a world without hate, a world without fear, a world without war. And I can imagine us attacking that world, because they would never expect it. -Jack Handy

This topic is closed to new replies.

Advertisement