Lua - nils in table constructor

I have the 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 result:

ta[1]=  nil
ta[2]=  nil
ta[3]=  nil
ta[4]=  1

I suggested that both tables should be the same. But it’s not really.

I am trying to create a table with an empty constructor and initialize the elements one by one, including nils at the beginning. But I got the same result with the tb table.

Who cares? Can I manage it manually?

+4
source share
3 answers

While WB is basically correct, since the length operator is not very consistent for arrays with holes, it is not undefined.

Lua manual " n, t[n] nil t[n+1] , , t[1] nil, n ."

, {"a", nil, "b", nil, "c"} 1, 3, 5. , , .

+5

Lua # undefined , , 1 .

+7

ipairs() . () .

-- The array part. This loop will stop when it reaches a nil array element.
local length = 0
for key, value in ipairs(t) do
  length = key
  -- Process it.
end

-- The hash part.
for key, value in pairs(t) do
  -- Check if the key is in the array we already processed.
  if type(key) ~= 'number' or key < 1 or key > length or key ~= math.floor(key) then
    -- Process it.
  end
end
+4

Source: https://habr.com/ru/post/1538019/


All Articles