7

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", 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?

5 Answers 5

6

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.

Sign up to request clarification or add additional context in comments.

Comments

4

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

Comments

4

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.

Comments

1

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

Comments

0

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)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.