Quantcast WoWInterface - View Single Post - Removing a table key?
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.
__________________
Author/maintainer of Grid, PhanxChat, oUF_Phanx, and many more.
Troubleshoot an addonTurn any code into an addonMore addon resources
Need help with your code? Post all of your actual code! Attach or paste your files.
Please don’t PM me about addon bugs or code questions. Post a comment or forum thread instead!
  Reply With Quote