Lua function call

I would like to process the following code in Lua and C:

Say I have a C function called Foo that is bound to Lua. I call it the following in a Lua script:

 Foo(15, "bar", function(z) return 2 * z + 1 end) 

On the C side, I extract the arguments, and I can save the number and string in my structure. But what type of data will I need to store an anonymous function? And how can I call it later?

+7
source share
5 answers

You cannot save a Lua function as a C data type, more than you can save a Lua table as a C data type.

What you can do is use the registry to save this value. The registry is a globally accessible table for all C users to store data. It is often useful to select one key for all your code and put a table on that key. This table will contain the values ​​you want to keep. This will help reduce conflicts with other C code using the registry.

+6
source

You can either leave the function somewhere on the stack, or save it in the registry or in some other table using luaL_ref.

+4
source

As a rule, you do not store the function in the variable C. You leave it on the stack and name it with pcall (). Something like:

 int l_Foo(lua_State *L) { lua_pop(L, 2); /* ignore the first two args */ /* (the function is now on top of the stack) */ lua_pushnumber(L, 2); /* push the number to pass as z */ lua_pcall(L, 1, 1, 0); /* call the function with 1 argument, expect 1 result */ lua_pop(L, 1); /* ignore the result */ } 

I have lost some errors for brevity, but see Lua Programming for a more complete example and the Lua Reference Guide for more details on functions.

+4
source

This page may also be useful: http://www.lua.org/pil/25.2.html

And this: http://www.luafaq.org/#T7.2

And it looks like the answer was given here: how to call the lua function from the c function

+1
source

One way would be to make the anonymous function work on the lua side and pass the result to the FOO(int, char*, fun_result_type fun_result) function FOO(int, char*, fun_result_type fun_result)

0
source

All Articles