http://lua-users.org/wiki/CppLuaDataPassing has this code to create a Lua table from C++:
// set first element "1" to value 45
lua_pushnumber( state, 1 );
lua_pushnumber( state, 45 );
lua_rawset( state, -3 );
// set the number of elements (index to the last array element)
lua_pushliteral( state, "n" );
lua_pushnumber( state, 1 );
lua_rawset( state, -3 );
It seems that the last block implies that Lua tables have some special-meaning key of “n” which stores the index to the last array element, based on that example.
But I couldn’t find any reference to that in Lua Manual.
-
Is my guess right or wrong?
-
If it’s right, can someone point me to a good reference explaining this “n” key?
-
If wrong, what is the meaning of that second block of code in the example?
-
And if it’s right, is doing this last index assignment required to create a valid table in C++ for Lua reading (assume that Lua code will NOT modify the table)
It used to be a convention to hold the size of the table. I believe in lua 5.1 they deprecated that as a practice in favor of the
#operator, as there were times when it would seemingly magically conflict with data people were stuffing in their tables.