I have a functions nested relatively deeply in a set of tables. Is there a way in C/C++ to get a "reference" to that function and push that (and args) onto the stack when I need to use it?
Moreover, for a C function to be called from Lua, we must register it, that is, we must give its address to Lua in an appropriate way. When Lua calls a C function, it uses the same kind of stack that C uses to call Lua. The C function gets its arguments from the stack and pushes the results on the stack.
The C API is the set of functions that allow C code to interact with Lua. It comprises functions to read and write Lua global variables, to call Lua functions, to run pieces of Lua code, to register C functions so that they can later be called by Lua code, and so on.
As the name implies, we use references mainly when we need to store a reference to a Lua value inside a C structure. As we have seen, we should never store pointers to Lua strings outside the C function that retrieved them. Moreover, Lua does not even offer pointers to other objects, such as tables or functions.
In Lua, the following are the available string formatting syntax or string literals for different datatypes: %s : This serves as a placeholder for string values in a formatted string. %d : This will stand in for integer numbers. %f : This is the string literal for float values.
This is what the reference system is for. The function call r = luaL_ref(L, LUA_REGISTRYINDEX)
stores the value on the top of the stack in the registry and returns an integer that can be stored on the C side and used to retrieve the value with the function call lua_rawgeti(L, LUA_REGISTRYINDEX, r)
.
See the PiL chapter, as well as the documentation of luaL_ref()
, lua_rawgeti()
, and luaL_unref()
for the full story.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With