View Single Post
09-12-14, 03:00 AM   #11
Phanx
Cat.
 
Phanx's Avatar
AddOn Author - Click to view addons
Join Date: Mar 2006
Posts: 5,617
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.
__________________
Retired author of too many addons.
Message me if you're interested in taking over one of my addons.
Don’t message me about addon bugs or programming questions.
  Reply With Quote