22

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.

Nick Van Brunt
  • 15,244
  • 11
  • 66
  • 92

3 Answers3

26

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
  • 60,510
  • 8
  • 78
  • 126
15

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
  • 6,909
  • 9
  • 49
  • 63
0

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
  • 333
  • 1
  • 3
  • 7
  • That functionality already exist and it's the Lua reference table as Javier said. – Edwin Jarvis Feb 10 '09 at 17:38
  • 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 Van Brunt Feb 11 '09 at 12:30