lua-users home
lua-l archive

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]


> >From time to time the table will be modified. The manual says:
> 
> The behavior of next is undefined if, during the traversal, you assign any
> value to a non-existent field in the table. You may however modify existing
> fields. In particular, you may clear existing fields.



Example codes (how I think they'll work)

tab = {a=1,b=2,c=3} -- just some keys with values

function noproblem1 ()
  for i,v in pairs(tab) do
    if v%2 == 0 then tab[i] = nil end -- erase values that are odd
  end
end

function noproblem2 ()
  for i,v in pairs (tab) do
    tab[i] = v*2 -- multiply every value by 2
  end
end

function problematic ()
  for i,v in pairs (tab) do
    tab[v] = i -- the KEY v may exist, or may not exist
    -- thus, we possibly create a NEW key, which CAN break traversion
  end
end

So the value you assign doesn't matter. All that matters is, that you can set
existing values to any possible value (including nil, which deletes the key
from the table).

Undefined behaviour means, that you might not iterate over all values in your
loop for instance. I have no detailed information how the tables are working,
but I guess (no idea if this is right!) the behaviour becomes undefined, when
the table is resized during traversial.


Eike