lua-users home
lua-l archive

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


Thanks to Nick Trout, I downloaded a Lua binary for Windows and tested the
code I didn't test before, which I should obviously have done... but then
no-one called me on it this time :)

Little Lua quirk:

if a is a table without a metatable, a[nil] is always nil, but a[nil] = b
is an error. The __index metamethod receives the nil key, and can act on
it, but the __newindex metamethod doesn't; the error is generated before
the metamethod is called. This is an undocumented difference from Lua 4, I
believe.

Anyway, the (slightly tested) ZappableTable, without the a[nil] interface.
You use a[ZAP] instead, and I took out the pseudo O-O interface as being
redundant:

-- create a special key
ZAP = {}

-- and maybe speed up access to it
local ZAP = ZAP

-- table creator
function ZappableTable(init)
  local self = {}
  local meta = {}
  init = init or {}
  function meta:__index(key)
    if key == ZAP then return init
    else return init[key]
    end
  end
  function meta:__newindex(key, val)
    if key == ZAP then
      init = val or {}
    else
      init[key] = val
    end
  end
  function meta:__next(key)
    return next(init, key)
  end
  -- This assumes you will not zap during an iteration
  function meta:__pairs()
    return next, init
  end
  return setmetatable(self, meta)
end

-- replacement pairs function, just for fun.
-- in Lua, we cannot get at protected metatables, so
-- it is not as good as if it were written in C.
-- Also, this will not be called by default by a for
-- loop.

local next = next
local getmetatable = getmetatable

function pairs(t)
  local meta = getmetatable(t)
  if meta and type(meta) == "table" and meta.__pairs then
    return meta.__pairs(t)
  else
    return next, t
  end
end