3
votes

I'm trying to call a user-defined Lua function from C. I've seen some discussion on this, and the solution seems clear. I need to grab the index of the function with luaL_ref(), and save the returned index for use later.

In my case, I've saved the value with luaL_ref, and I'm at a point where my C code needs to invoke the Lua function saved with luaL_ref. For that, I'm using lua_rawgeti as follows:

lua_rawgeti(l, LUA_REGISTRYINDEX, fIndex);

This causes a crash in lua_rawgeti.

The fIndex I'm using is the value I received from luaL_ref, so I'm not sure what's going on here.

EDIT:

I'm running a Lua script as follows:

function errorFunc()
  print("Error")
end

function savedFunc()
  print("Saved")
end

mylib.save(savedFunc, errorFunc)

I've defined my own Lua library 'mylib', with a C function:

static int save(lua_State *L) 
{
    int cIdx = myCIndex = luaL_ref(L, LUA_REGISTRYINDEX);
    int eIdx = luaL_ref(L, LUA_REGISTRYINDEX);

I save cIdx and eIdx away until a later point in time when I receive some external event at which point I would like to invoke one of the functions set as parameters in my Lua script. Here, (on the same thread, using the same lua_State*), I call:

lua_rawgeti(L, LUA_REGISTRYINDEX, myCIndex);

Which is causing the crash.

2
In order to answer this, we need to see where you get the "user-defined Lua function" that you're trying to call and how you store this in the registry. - Nicol Bolas
It appears that the issue was that the point where I was calling lua_rawgeti was being run after I had called lua_close(L). - jimt
Do not under any circumstance use the Lua C api on a lua_State L after you have called lua_close(L) ;) - Oliver
@jimt I'd suggest self answering or deleting so the question doesn't remain open. - BMitch

2 Answers

0
votes

My first suggestion is to get it working without storing the function in C at all. Just assign your function to a global in Lua, then in C use the Lua state (L) to get the global, push the args, call the function, and use the results. Once that's working, you've got the basics and know your function is working, you can change the way you get at the function to use the registry. Good luck!

0
votes

As @Schollii mentioned, I was making this call after doing a lua_close(L).