1
votes

I wanted to return table(with key/value pair) which contains functions to lua from C++ function. On the lua side, return value of the function was table. But, table was empty.

I tried string instead of function, but it didn't worked, too.

If I use index instead of key, it works. But I want to put a key, not a index.

lua_newtable(L);
for(list<NativeFunction_t>::iterator it = nativeFuncs.begin(); it != nativeFuncs.end(); it++)
{
    NativeFunction_t tmp = *it;
    cout << "Loading " << tmp.Name << " to lua...";
    lua_pushstring(L, tmp.Name);
    //If I do lua_pushstring(L, (Index)) instead of above, it works.
    //lua_pushstring(L, tmp.Name);
    lua_pushcfunction(L, tmp.Func);
    lua_settable(L, -3);
    cout << "Success" << endl;
}
//lua_setglobal(L, loadAs);
cout << "Done" << endl;
return 1;

Is something wrong with the way I create and return the table?

And here is lua code.

print("Loading NativeLoader...")
NativeLoader = require("Module")
print("Loading library...")
NativeLoader.Load("Hello", "TestLibrary")
print("Looking library...")
print("TestLibrary: " ..#TestLibrary)
for n, item in ipairs(TestLibrary) do
    print(item)
end
--t.hello()
--t.bye()
1
Can you show complete code, including "NativeFunction_t` defn? It's very difficult to understand what's going on if you dontChris Beck
Use pairs() instead of ipairs().siffiejoe

1 Answers

2
votes

It looks like you are using string keys in the table.

ipairs only traverses through integer keys from 1 to n. As suggested by siffejoe in the comments, you should be using pairs instead. However you should note that pairs does not loop through the elements in the order they were inserted in the table.

If you need the elements to be in a specific order, you might want to return an additional table containing the string keys in the specific order. Or you may want to make the original table you return into an array that contains tables that contain the name and the function at different table keys.

Also note that the length operator only works on sequences of integer keys. So for your tables using only string keys it would always return 0.

I suggest you read through the lua reference manual for the length operator, pairs and ipairs. Here are links for lua 5.3 manual: