LUA CPP "how to" 5/7
4) How to call an entity's script LUA function passing parameters
following code is some what weird but you only have to pay attention on a few things
the idea is Push the parameters in the order they are declared in the lua function (from left to right)
and pay attention in the Interpreter:Invoke method. You have to set the first parameter (number of staked values) one more of the amount of parameters passed.
consider the following LUA function:
function Script:turnMe(turn)
System:Print("calling me from C")
self.entity:Turn(turn.x,turn.y,turn.z,true)
end
note that "turn" is a Vec3 variable
so you have to push the correct type of variable to lua stack and then tell Interpreter::Invoke that there are 2 things on the stack (as the code explains, one is always present: thank's Josh for that beautiful piece of code!)
here is a generic function to call any LUA script function that has one parameter of type Vec3:
bool call_turnMe(Entity* e, string funcName, Vec3 vec3){
if (e->component == NULL) return false;
bool success = false;
//Get the component table
int stacksize = Interpreter::GetStackSize();
//Get the global error handler function
int errorfunctionindex = 0;
#ifdef DEBUG
Interpreter::GetGlobal("LuaErrorHandler");
errorfunctionindex = Interpreter::GetStackSize();
#endif
e->Push();
Interpreter::GetField("script"); //test if entity has a script
if (Interpreter::IsTable())
{
System::Print(" entity has script");
Interpreter::GetField(funcName);
if (Interpreter::IsFunction()) //test if funcName is a function
{
System::Print(" " + funcName + " defined");
Interpreter::PushValue(-2); //Push script table onto stack
Interpreter::PushVec3(vec3); //we only pass one variable but stack has one more
#ifdef DEBUG
errorfunctionindex = -(Interpreter::GetStackSize() - errorfunctionindex + 1);
#endif
success = Interpreter::Invoke(2, 0, errorfunctionindex); // send 2 params, receive none (next tut for receive parameters)
}
}
Interpreter::SetStackSize(stacksize); //keep stack under control
}
Interpreter has a nice amount of pushes:
pushAABB, pushFloat, pushInt, pushString, pushCObject, pushObject, pushBool, pushNull,
pushMat3, pushMat4, pushVec2, pushVec3, pushVec4, pushValue
just remember: push parameters with the correct type and in order in which they was declared in the LUA function.
next tut, show how to pass 3 ints and receive a float, and also show how to receive more than one value from a lua script, because Return in lua may contain a list of values.
that's it
2 Comments
Recommended Comments