lua-users home
lua-l archive

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


> btw, I notice that there is a new keyword, "undef", not mentions in manual,
> is that just a undocumented feature or the doc just not the latest?

I am grad you asked :-)

Lua 5.4 has an experimental change that is off by default (to keep
compatibility). We plan to keep this off in Lua 5.4 final.
You can turn it on by compiling this version with the option
-DLUA_NILINTABLE. As the name hints, this option allows nils in tables:

>  t = {nil, nil, nil}
> #t
3
> for k,v in pairs(t) do print(k, v) end
1	nil
2	nil
3	nil
> t[#t + 1] = nil
> for k,v in pairs(t) do print(k, v) end
1	nil
2	nil
3	nil
4	nil


Once you have nils in tables, t[i]=nil does not remove elements from
a table anymore. For that, you need to write t[i]=undef.

No, this is not like JavaScript! 'undef' is NOT a value.

t[i]=undef is a special syntax form that means "remove the key 'i'
from table 't'". You can only use 'undef' in three specific forms:

  t[i] = undef     -- remove a key from a table
  t[i] == undef    -- test whether a table has a key
  t[i] ~= undef    -- test whether a table has a key

Any other use of 'undef' gives a syntax error.

You still can create tables with holes, but you must get out of your
way to do it.

The nice thing about this syntax is that it is compatible with
previous versions of Lua (as long as you do not use 'undef' for
other stuff). In Lua 5.0/1/2/3, if you write 't[i] = undef', you remove
the element from the table. Even if we never change Lua to this
new mode, even if you never use Lua 5.4, we think this syntax is
a nice way to document whether an assignment is being done to remove
an element from a table.

(A search for the pattern '][ =~]*nil' finds most of the places
in your code where you could/should use undef instead of nil.)

-- Roberto