lua-users home
lua-l archive

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


Aaron Saarela wrote:
> lua_getglobal(state, "foo.dosomething");
> lua_pcall(state, 0, 0, 0);
> // returns -1, err message indicates a call to nil

There is no global called "foo.dosomething" (as you can verify by
printing _G["foo.dosomething"]). You have to first get the global table
"foo", and then only get its member "dosomething". For example:

lua_getglobal(L, "foo");
if (lua_type(L, -1)!=LUA_TTABLE)
  return luaL_error(L, "foo module is not loaded");
lua_getfield(L, -1, "dosomething");
if (lua_type(L, -1)!=LUA_TFUNCTION)
  return luaL_error(L, "foo module has no dosomething method");
lua_replace(L, -2); // This removes the foo table from the stack
lua_pcall(L, 0, 0, 0); // should return 0

You should always check that a gettable (and its variants getfield,
getglobal, rawget, rawgeti) is pushing something on the stack before
using it.