I'm trying code from lua.org and from my 4th edition Programming in Lua hardcopy, and as far as I've read all these table examples should work but 3 out of 4 don't, and I cant find anything the docs that says why. Some help on what I am missing appreciated. I assume some spec has changed as I already found out with table.getn() not being available anymore. My linux box has Lua 5.3.5
local t1={}
t1[1]="Foo"
t1[2]="Bar"
print("Size: "..#t1)
print("Works:"..table.concat(t1,'$$'))
local t2={}
t2[5]="Foo"
t2[40]="Bar"
print("Size: "..#t2)
print("Doesnt Work:"..table.concat(t2,'$$'))
local t3={}
t3["A"]="Foo"
t3["B"]="Bar"
print("Size: "..#t3)
print("Doesnt Work:"..table.concat(t3,'$$'))
local t4={}
t4.A="Foo"
t4.B="Bar"
print("Size: "..#t4)
print("Doesnt Work:"..table.concat(t4,'$$'))
Results
Size: 2
Works:Foo$$Bar
Size: 0
Doesnt Work:
Size: 0
Doesnt Work:
Size: 0
Doesnt Work:
Please read Lua Reference Manual: 3.4.7 The Length Operator
Applied to your examples:
t1
has only one boarder (2), becauset1[2] ~= nil and t1[2+1] == nil
.t1
has only 1 border ->t1
is a squence ->#t1
is the length oft1
.t2
has 3 borders (0, 5, 40), becauseboarder == 0 and t[0+1] == nil
,t[5] ~= nil and t[5+1] == nil
,t[40]~=nil and t[40+1]==nil
t2
has more than one borders->#t2
is any of its borders, not its length.t3
has 1 border (0), becauseborder == 0 and t3[0+1] == nil
, no more numeric keys so no more borders.t3
has only one border ->t3
is a sequence with length 0.is the same as
t4
ast.name
is syntactic sugar fort["name"]
. Only works for valid Lua names!t1
is the only sequence among your examples and hence the only one#
yields the number of element for.If you are unsure if you have a sequence you should count the elements like so:
This is how you would print the boarders of a table
t
: