lua-users home
lua-l archive

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]

On 19/07/2021 06:50, William Ferguson wrote:
> If I populate a table then read it back like this
> I get the following output
> lua table has length 1.000000 1.000000 - string 3.000000 - number
> In Lua 5.3 I get
> lua table has length 1.000000 1.000000 - string
> Is this a bug, or am I missing something?

This is a common mistake people new to Lua make.

> The length operator applied on a table returns a border in that
> table. A border in a table t is any natural number that satisfies the
> following condition:
> (border == 0 or t[border] ~= nil) and t[border + 1] == nil
> In words, a border is any (natural) index present in the table that
> is followed by an absent index (or zero, when index 1 is absent).

(read the whole section, this is just a key part)

If you want to use a table as an array, you need to make sure all
indexes are set (no nils), or set a metatable that specifies the __len
function. Also using lua_geti makes more sense in this case, as lua_next
will traverse all keys, both integer and other types.