Introduction to GameMonkey Script Part 2
Embedding GameMonkey
Calling a Scripted FunctionThere will often be times that you would like to call a known scripted function from your application; perhaps you specify that your game will need to call an InitialiseGame scripted function, or perhaps the Attack function in scoping_6.gm that was originally presented in part one's scripts. In GameMonkey Script there are currently two ways to call a scripted function from native code; the manual way which uses the raw API to push variables and prepare the stack, and the simple way which uses a utility called gmCall. I will take you through calling a scripted function using gmCall, since that is the simplest and most common way you'll need to call a function. For purists, I have included some example source that doesn't use gmCall with this article, but for most purposes I advise using gmCall. Using gmCallThe authors of GameMonkey Script realised that the manual way of calling functions can be long-winded and prone to error and so have thoughtfully provided gmCall to vastly simplify the calling of scripted functions.
Here is an example that calls a scripted function myMultiply which takes two numbers as parameters and returns their sum. int main() { gmMachine gm; // Execute a simple script file gmLoadAndExecuteScript ( gm, "scripts/function_test.gm" ); gmCall call; if ( call.BeginGlobalFunction( &gm, "myMultiply" ) ) { // Push the parameters // with a plain int call.AddParamInt( 10 ); // with a gmVariable gmVariable var( 2 ); call.AddParam( var ); // Execute the call call.End(); // Handle the return value int myReturn = 0; if (call.GetReturnedInt( myReturn ) ) { std::cout << "myMultiply returned " << myReturn << std::endl; } else { std::cout << "myMultiply returned an incorrect value" << std::endl; } } else { std::cout << "Error calling 'myMultiply'" << std::endl; } return 0; } The gmCall AddParam* functions allow you add parameters without having to deal with gmVariable objects (although it is entirely possible to pass your own gmVariables). Any required allocations and validations are performed automatically for you, allowing you to quickly access the scripted functions you need. |