Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Lua - nils in table constructor

Tags:

lua

lua-table

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?

like image 666
Playermet Avatar asked Dec 04 '22 06:12

Playermet


1 Answers

In Lua the behaviour of length operator # is undefined for arrays, where sequence is broken, that is, it doesn't start at 1 or has empty slots inside.

like image 61
W.B. Avatar answered Feb 15 '23 23:02

W.B.