Hi,
I have problem with removing table line at specified index, ok you can say use table.remove, but that removes on specified position, not index. And i dont need to set it to nil, I need to delete it, so for dont detect it.
Thx for reply
mistr88
table[key] = nil
will remove the value at key from table. It will not necessarily clean up the value itself.
I’m not sure what you mean by “index” but if you want to remove something based on a string, number etc then you have to use a function like this:
local stuff = {"a","magic","lol"}
function removeFromTable(TABLE, index)
for i = 1, #TABLE do
if TABLE[i] == index then
table.remove(TABLE, i)
end
end
end
removeFromTable(stuff, "magic")
i need to make it undetectable for for loops
For statements will not iterate over the key-value pair since the key-value pair no longer exists when you set the key’s value to nil.
local t = {"a", "b"}
t[1] = nil
for key, value in pairs(t) do --> 2 b
print(key, value)
end
i can have index 6 at table with 1 line
oh, i put there break and i saw, that its deleted
The only way to explicitly remove an item from a table in Lua is to set an index’s value to nil
(disregarding weak keys/values). Under the hood, table.remove
is doing that too, but also shifts the values to remove the gap.
You say that you don’t want to set it to nil
but want to delete it. However, this concept does not exist with Lua tables. It does for other languages (e.g. JavaScript has a delete
keyword), but in Lua you just set it to nil
to delete it.
As @Dandystan said, index-based for
loops won’t operate properly if you just remove an index from the list (unless it’s the last item).
What’s your use case? What exactly are you trying to do?
ok didnt knew, i am using it more as asociative array so this will be problem, when i use table.remove
ok, i dont work much with tables in lua so i didnt knew