title: Calling Lua from C
body: <p>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. </p>
  
  <p>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:</p>
  
  <pre><code>lua_rawgeti(l, LUA_REGISTRYINDEX, fIndex);
  </code></pre>
  
  <p>This causes a crash in lua_rawgeti.</p>
  
  <p>The fIndex I'm using is the value I received from luaL_ref, so I'm not sure what's going on here. </p>
  
  <p>EDIT:</p>
  
  <p>I'm running a Lua script as follows:</p>
  
  <pre><code>function errorFunc()
    print("Error")
  end
  
  function savedFunc()
    print("Saved")
  end
  
  mylib.save(savedFunc, errorFunc)
  </code></pre>
  
  <p>I've defined my own Lua library 'mylib', with a C function:</p>
  
  <pre><code>static int save(lua_State *L) 
  {
      int cIdx = myCIndex = luaL_ref(L, LUA_REGISTRYINDEX);
      int eIdx = luaL_ref(L, LUA_REGISTRYINDEX);
  </code></pre>
  
  <p>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:</p>
  
  <pre><code>lua_rawgeti(L, LUA_REGISTRYINDEX, myCIndex);
  </code></pre>
  
  <p>Which is causing the crash.</p>