1

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 Answers 2

2

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
Sign up to request clarification or add additional context in comments.

3 Comments

function globaltable.subtable.function() was supposed to be just for orientation - lets assume its "function globaltable.subtable.hello()"
Then my second point applies. It looks like subtable cannot be found in globaltable. Try creating a Lua stackDump function to show the content of the stack, and call it after every Lua operation.
Ive edited the question above - im creating this globaltable in C++ and i don't know how to create the subtable in globaltable
0
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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.