D
D
dollar2019-08-01 05:34:52
Lua
dollar, 2019-08-01 05:34:52

Why does adding and removing at the same time cause an error in an array?

local t = {a=1}

for k,v in pairs(t) do
  t[k] = nil
  t[1] = 2
end

Doesn't the spec say you can't do that?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
Z
zed, 2019-08-01
@dollar

In the documentation for lua 5.1, the description of the next function says:
those. You can modify or delete existing elements, but you cannot add new ones.
In the docks for lua 5.3, I did not find such a remark (badly searched?), But in general, from a practical point of view, adding new elements to a table while iterating over it is a very bad idea.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question