开发者

Calling Lua function

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

Let's say that I have C function named Foo that is bound to Lua. I call it like following in Lua script:

Foo(15, "bar"开发者_JS百科, function(z) return 2 * z + 1 end)

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


You can't store a Lua function as a C data type, anymore than you can store a Lua table as a C data type.

What you can do is use the registry to store this value. The registry is a globally-available table to all C users for storing data. It's often a good idea to pick a single key for all of your code and put a table at that key. This table would contain the values you want to preserve. This will help reduce conflicts from other C code using the registry.


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


Generally, you don't store the function in a C variable. You leave it on the stack and call 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've left out some error checking for the sake of brevity, but see Programming in Lua for a more complete example and the Lua Reference Manual for more details about the functions.


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

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

And it seems like it was answered here: how to callback a lua function from a c function


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜