2
votes

I was playing around in Lua with a simple 'isPrime' function I made, and, ignoring the actual 'isPrime' function, which is irrelevant to this query, wrote the following code:

out = {}
for i = -10,20 do
    out[i] = isPrime(i)
end

for k,v in ipairs(out) do
    print(k,v)
end

My expectation was that the program would print every single key and its respective value, -10 through 20, but found instead that only 1 through 20 were printed. -10 through 0 were in the table, I found, after checking specifically for those key-value pairs, but oddly, they were never printed.

Can anyone explain why this happened? I feel I do not fully understand how Lua iterates and accesses its keys through the ipairs() function.

1

1 Answers

4
votes

ipairs(t) will iterate over the key–value pairs (1,t[1]), (2,t[2]), ..., up to the first nil value. That's not what you want. Just use the style of your first loop

for i = -10,20 do
    print(i, out[i])
end