lua-users home
lua-l archive

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


> It can be useful, for example, to have 'nil propagation' in a chain of table
> accesses without having to check for key validity at each step.

It can also be used to build a table that appears to accept nil or NaN
values as keys !

Something like :

local nilkey, nankey = {}, {} -- unique keys

t=setmetatable({},{
__index=function(t,k)
  if k==nil then
    return t[nilkey]
  elseif k~=k then
    return t[nankey]
  end
end,
__newindex=function(t,k,v)
  if k==nil then
    t[nilkey]=v
  elseif k~=k then
    t[nankey]=v
  else
    rawset(t,k,v)
  end
end})

print(t[1], t[nil], t[0/0]) --> nil nil nil
t[1] = "One"
t[nil] = "Nil!"
t[0/0] = "NaN!"
print(t[1], t[nil], t[0/0]) --> One Nil! Nan!