1
votes

im trying to call a lua function from C++ where function is in subtable of global table. Im using lua version 5.2.* compiled from source.

Lua function

function globaltable.subtable.hello()
 -- do stuff here
end

C++ code

lua_getglobal(L, "globaltable");
lua_getfield(L, -1, "subtable");
lua_getfield(L, -1, "hello");
if(!lua_isfunction(L,-1)) return;
    lua_pushnumber(L, x);
    lua_pushnumber(L, y);
    lua_call(L, 2, 0);

However im unable to call it, i always get an error

PANIC: unprotected error in call to Lua API (attempt to index a nil value)

On line #3: lua_getfield(L, -1, "hello");

What am I missing?

Side question: I would love to know also how to call function deeper than this - like globaltable.subtable.subsubtable.hello() etc.

Thank you!


This is what im using to create the globaltable:

int lib_id;
lua_createtable(L, 0, 0);
lib_id = lua_gettop(L);
luaL_newmetatable(L, "globaltable");
lua_setmetatable(L, lib_id);
lua_setglobal(L, "globaltable");

how do i create the globaltable.subtable?

2

2 Answers

2
votes

function is a keyword in Lua, I am guessing on how did you manage to compile the code:

-- test.lua
globaltable = { subtable = {} }
function globaltable.subtable.function()
end

When this is run:

$ lua test.lua
lua: test.lua:2: '<name>' expected near 'function'

Maybe you changed the identifiers for this online presentation, but check that on line 2 "subtable" really exists in the globaltable, because on line 3, the top of stack is already nil.

Update:

To create multiple levels of tables, you can use this approach:

lua_createtable(L,0,0); // the globaltable
lua_createtable(L,0,0); // the subtable
lua_pushcfunction(L, somefunction);
lua_setfield(L, -2, "somefunction"); // set subtable.somefunction
lua_setfield(L, -2, "subtable");     // set globaltable.subtable
0
votes
lua_newtable(L);
luaL_newmetatable(L, "globaltable");
lua_newtable(L); //Create table
lua_setfield(L, -2, "subtable"); //Set table as field of "globaltable"
lua_setglobal(L, "globaltable");

This is what i was looking for.