lua-users home
lua-l archive

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]



Max Ischenko wrote:
I have a function in Lua that returns a function value:
function foobar()
 return loadstring('2+3')
end

I'm trying to call the foobar from C and to save returned value (to be
able to call it later).
How am I supposed to do this?

   lua_pushstring(L, "foobar");
   lua_gettable(L, LUA_GLOBALSINDEX);
   lua_call(L, 0, 1);

   lua_tocfunction(L, -1); // returns NULL
   lua_typename(L, lua_type(L, -1)); // prints "function"

Is there a way to store a Lua function as C object (and call it) or I
should be using some other way?

A Lua function can be stored in the Registry just like any other Lua value.

  /* take func from top of stack and store it in the Registry */
  int func_ref = luaL_ref(L, LUA_REGISTRYINDEX);
  /* now store func_ref some place safe in C */

Later on, you can get it back and call it.

  lua_rawgeti(L, LUA_REGISTRYINDEX, func_ref);
  lua_pcall(L, 0, 0, 0);

- Petet Shook