There is such a code:

a = { [1] = "a", [2] = "b", [3] = nil, [4] = "d", ["x"] = "asd", } a[3] = nil a[5] = nil a[6] = 213 for i = 1, #a do print(i, a[i]) end 

conclusion:

 1 a 2 b 3 nil 4 d 5 nil 6 213 

If I comment 4 (separate attention that it is repeated after creating the array) or 6 line

 a = { [1] = "a", [2] = "b", [3] = nil, -- 4 строка [4] = "d", --["x"] = "asd", -- 6 строка } a[3] = nil a[5] = nil a[6] = 213 for i = 1, #a do print(i, a[i]) end 

That conclusion:

 1 a 2 b 3 nil 4 d 

First of all. The documentation says that #a computed for a sequence (i.e., keys 1, n and no holes). nil - removes the key, i.e. makes a hole, but for some reason the length of the array is considered wrong.

Secondly. Logically, the string key ["x"] should not affect the calculation of #a at #a , but it also affects in some strange way.

What am I doing wrong? Thank.

UPD In this case, if you take turns commenting on lines 8 and 9 in this code, the output behaves predictably:

 b = { [1] = "a", [2] = "b", [3] = "c", [4] = "d", [5] = "e" } b[4] = nil -- 8 строка --b[5] = nil -- 9 строка for i = 1, #b do print(i, b[i]) end 
  • one
    lua.org/manual/5.1/manual.html If the array has holes holes ’(that is, it’s nil values), then , it can be considered as the end of the array). - coder675 February
  • one
    If there are holes in the array, then the length can be installed on any of them. - coder675 February
  • @ coder675 I am an idiot, thank you, I ran through this page today and did not see this, but in the Russian version there is no such thing. - imsysmem

0