I’m trying to write some c++ classes for interfacing with LUA and I am confused about the following:
In the following example: Wherigo.ZCommand returns a “Command” objects, also zcharacterFisherman.Commands is an array of Command objects:
With the following LUA code, I understand it and it works by properly (luaL_getn returns 3 in the zcharacterFisherman.Commands c++ set newindex function):
zcharacterFisherman.Commands = {
Wherigo.ZCommand{a="Talk", b=false, d=true, c="Nothing available"},
Wherigo.ZCommand{a="Talk", b=false, d=true, c="Nothing available"},
Wherigo.ZCommand{a="Talk", b=false, d=true, c="Nothing available"},
}
But when the array is defined with the following LUA code with a slightly different syntax luaL_getn returns 0.
zcharacterFisherman.Commands = {
Talk = Wherigo.ZCommand{a="Talk", b=false, d=true, c="Nothing available"},
Talk2 = Wherigo.ZCommand{a="Talk", b=false, d=true, c="Nothing available"},
Talk3 = Wherigo.ZCommand{a="Talk", b=false, d=true, c="Nothing available"},
}
All objects are defined in c++ and the c++ objects hold all the object members so I am trying to just connect LUA to those c++ objects. Is this enough or do I need to post some of my code??
luaL_getn is for getting the highest numeric element of an array in Lua. An array is a table with only integer indices. When you define a table in Lua (the first example) without explicitly setting indices, you will get an array with elements 1, 2, and 3. Naturally, luaL_getn returns a 3 here. luaL_getn is NOT defined to return the number of elements in the table, it is defined to return the highest numeric index in the table (see http://www.lua.org/manual/5.1/manual.html#pdf-table.maxn)
The second example is NOT using numeric indices, and this table is not a Lua array — it is more like a hash table. Since luaL_getn only works on true arrays, you wouldn’t expect it to work here.
Unfortunately, there is no simple way to get the number of elements in a table (lua_objlen solves a related problem, but does not fix this one). The only way to do it is to either: