Also another thing that occurred to me is that either method (ipairs or #) will end up skipping values if you remove values inside the loop... but # has the advantage here (yet again) in that you can do the loop backwards to avoid this.
Code:
print("ipairs")
local t = { "apple", "banana", "coconut", "durian" }
for i, v in ipairs(t) do
print(i, v)
if i == 2 then
tremove(t, i)
end
end
You only get "apple", "banana", and "durian" printed, and the loop doesn't even iterate a 4th time.
Code:
print("#")
local t = { "apple", "banana", "coconut", "durian" }
for i = 1, #t do
local v = t[i]
print(i, v)
if i == 2 then
tremove(t, i)
end
end
You still only get "apple", "banana", and "durian" but the loop does iterate a 4th time and you get a "nil" print.
Code:
print("# reverse")
local t = { "apple", "banana", "coconut", "durian" }
for i = #t, 1, -1 do
local v = t[i]
print(i, v)
if i == 2 then
tremove(t, i)
end
end
Now you get all 4 values printed.