I am tring to get table length with lua_rawlen, code like this
lua_createtable(L, 0, 0);
lua_pushstring(L, "k0");
lua_pushstring(L, "v0");
lua_settable(L, -3);
lua_pushstring(L, "k1");
lua_pushstring(L, "v1");
lua_settable(L, -3);
printf("%d\n", lua_rawlen(L, -1));
output is 0, seems it should be 2, what’s wrong with it? thanks for any advice.
The function
lua_rawlenreturns the length of a sequence without calling the optional metamethod__len. It is the equivalent of Lua functionrawlen, which is the same as the#operator when there is no such__lenmetamethod.Your table is not a sequence, since you only put string keys. The keys of a sequence must be consecutive integers starting from 1. Instead of
"k0"and"k1"for keys, try with1and2respectively.Example: