Storing Lua function for later use in C++

Solution for Storing Lua function for later use in C++
is Given Below:

I am using lua-intf to integrate lua into my project. I want to setup a lua function that takes in a function as an argument and that then gets stored in C++ and called at a later time.
This would be the lua code for example where I would store both of these functions in C++:

foo(function() print("bar") end)

I have tried using LuaRef as an argument but couldn’t get it to work, I have also tried setting the argument as a lua_Cfunction.

Using the Lua registry is probably the easiest way. For more on the registry, see this page.

As an example, here is a C function called lua_foo that shows how to store a reference in the registry:

int lua_foo(lua_State* L) {
    // Make sure a function has been passed.
    luaL_checktype(L, 1, LUA_TFUNCTION);
    // Make sure that the function is at the top of the stack.
    lua_pushvalue(L, 1);
    // Create a reference to the function using the Lua registry.
    int ref = luaL_ref(L, LUA_REGISTRYINDEX);
    // FIXME: do something with the reference or store it for later use.
    return 0;

In order to store the function passed to lua_foo for later use, see luaL_ref; and, for the freeing of such a resource held by the Lua registry, see luaL_unref.

From within your C function, use luaL_ref to create a reference, which is an integer, for later use. The function, whose reference key is returned by luaL_ref, can be retrieved using lua_geti. Once retrieved, the function is pushed onto the Lua stack and can be called.

Alternatively, you can dump the function–as you would with a call to string.dump–and store the string result for later loading and use. Admittedly, this approach is a little more involved.