-
Notifications
You must be signed in to change notification settings - Fork 0
CPP from Lua function methods
Functions called from Lua must have the signature of int function(lua_State*);
, so an alternate method of passing arguments into and results out of C++ is required. The LuaInstance class has 2 methods for handling this function control flow.
This method is intended to be called at the immediate start of a C++-from-Lua function. The lua_State* should be the one passed to the function by Lua. This allows LuaSimple to find the LuaInstance object that corresponds to that pointer and return a reference to it.
The types vector is a list of Lua types the function should expect when taking arguments from Lua. The types are ordered the same as the Lua arguments, element 0 being the first argument. Each type is identified by an integer, but macros that correspond type names to numbers are found in luainclude/lua.h. (As an example, the macro LUA_TNUMBER == 3, which identifies the number type). If more arguments are provided than the vector has element, the later arguments are not type-checked.
Arguments provided by Lua are loaded into the returned LuaInstance's lua_argument_values vector. They are placed in the order provided, with element 0 being the first. These are accessible for the whole duration of the function.
Returns the values given to it as the result of the function in Lua. The function gives the number of values it returns to Lua as its result, which is what Lua wants the C++ function to return. Therefore it can be used as a tail call like in the example provided below.
This is then how a C++-from-Lua function should be structured, using here 1 argument and 1 return value:
int FunctionName(lua_State* pointer_from_lua){
auto& lua_wrapper = LuaInstance::GetLuaData(pointer_from_lua, {LUA_TSTRING});
string some_text = get<string>(lua_wrapper.lua_argument_values[0]);
//do stuff
lua_Integer return_number = 20;
return lua_wrapper.ReturnResults({return_number});
}