tags:

views:

1154

answers:

3

Calling a Lua function from C is fairly straight forward but is there a way to store a Lua function somewhere for later use? I want to store user defined Lua functions passed to my C function for use on events, similar to how the Connect function works in wxLua.

+13  A: 

check the registry (luaL_ref()). it manages a simple table that lets you store any Lua value (like the function), and refer to it from C by a simple integer.

Javier
Lua ref is just too cool - can't believe I've been using Lua all this time without knowing about this feature. Thanks!
Nick
A: 

The easiest way to do this is for your function to take a "name" and the lua function text. Then you create a table in the interpreter (if it doesn't exist) and then store the function in the table using the named parameter.

In your app just keep hold of a list of function names tied to each event. When the event fires just call all the functions from your table whose key matches the names in the list.

Ryan Roper
That functionality already exist and it's the Lua reference table as Javier said.
Augusto Radtke
The problem with naming the functions in this case is that we want the user to be able to define multiple functions with essentially the same name - e.g. "onclick" for button1 is different than "onclick" for button2.
Nick
+3  A: 

Building on Javier's answer, Lua has a special universally-accessible table called the registry, accessible through the C API using the pseudo-index LUA_REGISTRYINDEX. You can use the luaL_ref function to store any Lua value you like in the registry (including Lua functions) and receive back an integer that can be used to refer to it from C:

// Assumes that the function you want to store is on the top of stack L
int function_index = luaL_ref(L, LUA_REGISTRYINDEX);
andygeers