Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Store a Lua function?

Tags:

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.

like image 973
Nick Van Brunt Avatar asked Feb 10 '09 16:02

Nick Van Brunt


People also ask

What is function Lua?

It means that, in Lua, a function is a value with the same rights as conventional values like numbers and strings. Functions can be stored in variables (both global and local) and in tables, can be passed as arguments, and can be returned by other functions.

What does colon mean in Lua?

The :(colon) operator in Lua is used when you want to pass an invisible parameter to the method of an object that you are calling.

What is Lua Pcall?

Lua Error Handling Using pcall pcall stands for "protected call". It is used to add error handling to functions. pcall works similar as try-catch in other languages. The advantage of pcall is that the whole execution of the script is not being interrupted if errors occur in functions called with pcall .


2 Answers

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.

like image 176
Javier Avatar answered Oct 14 '22 16:10

Javier


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); 
like image 44
andygeers Avatar answered Oct 14 '22 16:10

andygeers