Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reference to Lua function in C/C++

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?

like image 738
jameszhao00 Avatar asked Sep 13 '09 03:09

jameszhao00


People also ask

How do you call a function in C Lua?

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.

Can Lua use C?

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.

Does Lua reference?

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.

What is %f Lua?

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.


1 Answers

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.

like image 159
RBerteig Avatar answered Sep 27 '22 22:09

RBerteig