I am seeing some unexpected behaviour when using a table
as an array
in pico8 lua when compared to regular PUC-Rio lua
If I run the following code using PUC-Rio lua5.4.4 (ubuntu)
local t={}
for i=1,10 do t[i] = i*10 end
t[2]=nil
t[4]=nil
t[6]=nil
t[8]=nil
print()
for i=1,#t do print(t[i]) end
I get the expected output
10
nil
30
nil
50
nil
70
nil
90
100
However if i run the same code with pico-8 I get:
10
This appears triggered only when I delete (ie set to nil) the t[8] element. if I comment out that line then I get the expected on pico8
10
nil
30
nil
50
nil
70
80
90
100
It appears, in pico8 lua, that the #t
size of the array
changes to 1
when the t[8]
element is set to nil
.
Both are expected results, the length operator #
in lua returns a number n
where t[n] ~= nil
and t[n+1] == nil
, if there are holes (nil value) inside, the result is undefined.
To find the maximum numeric index, in lua 5.1 you can use table.maxn, in other versions you have to write one.
table.maxn = function(t)
local n = 0
for k, v in pairs(t) do
if type(k) == 'number' and k > n then
n = k
end
end
return n
end