Removing a table key?
Assuming I want to save guids. At some point in the future I want to remove outdated guids.
Lua Code:
Quote:
Lua Code:
Question. If I set the table value for a key to nil. When ipairs is called again. Will ipairs return keys with a value of nil? |
table.remove is used to remove values from an indexed array, not a a associative array like yours, the usage of it is this:
Code:
table.remove(guids, index) Code:
guids[guidA] = nil |
Yeah updated my post. Found it in the last sentence of the lib tutorial.
When running ipairs on a table with keys that are set to nil. Are those entries still returned? I mean the key should still exist?! |
Quote:
ipairs iterates until it hits a nil value and then stops. If keys 1, 2, 3 and 5 of your table have values, ipairs will iterate up to 3 and then stop. |
Setting the value to nil effectively removes the key from the table.
Also, ipairs halts when it hits the first nil value (and it can't read the key afaik), and it also is slower than any other option. Use pairs, or better yet, next for your iteration needs. Code:
local t = { |
Even better on an indexed table (and much faster than either pairs or next):
Code:
for i = 1, #t do |
Quote:
|
Thank you.
|
Quote:
Example when a table has "holes": Code:
ILUA: Lua 5.1.4 Copyright (C) 1994-2008 Lua.org, PUC-Rio |
That's true, but if you're using an indexed table and putting holes in it and still expecting to use it as an indexed table, you are Doing It Wrong. :p
|
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") Code:
print("#") Code:
print("# reverse") |
If I have a table referenced by indexes [1], [2] and [3].
If I table.remove(t,2). [3] becomes [2] right? |
Yes. tinsert and tremove will both automatically adjust the array appropriately. (unlike just setting nil)
|
All times are GMT -6. The time now is 11:19 AM. |
vBulletin © 2024, Jelsoft Enterprises Ltd
© 2004 - 2022 MMOUI