Lua - nils in table constructor
lua, lua-table
Solution
While W.B. is mostly right, in that the length operator is not very consistent for arrays with holes, it's not undefined either.
The length of a table is defined in the Lua manual to be "any integer index `n` such that `t[n]` is not `nil` and `t[n+1]` is nil; moreover, if `t[1]` is `nil`, `n` can be zero."
This means that the length of `{"a", nil, "b", nil, "c"}` can be either 1, 3, or 5. So while the length operator will no longer give you a very useful and specific result, it won't give you garbage either.
Problem
I have a following code: ``` local ta = { nil, nil, nil, 1, a = 2 } local tb = { [4] = 1, a = 2 } for i = 1, #ta do print('ta['..i..']= ', ta[i]) end for i = 1, #tb do print('tb['..i..']= ', tb[i]) end ``` And get the following output: ``` ta[1]= nil ta[2]= nil ta[3]= nil ta[4]= 1 ``` I assumed that both tables should be the same. But it's not quite. I try create table with empty constructor, and initialize elements one by one, including nils at the beginning. But got the same result with the table tb. What the difference? Can I manage this manually?