lua-users home
lua-l archive

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


> That is, I'm sorry, but I fail to see why one might need a __removeindex
> metamethod. OTOH, being able to set a __len metamethod for tables would be
> useful (along with a "rawlen" function for tables, probably).

Correcting myself: the proxy was needed because of __len _and_ __newindex. It
would also be nice to have for table's newindex to look for a __newindex
metamethod. Now I understand the need for a __removeindex, but it would be
better to see nil assignments (to existing keys) treated by __newindex for
tables in the same way as for other objects -- although there should be a good
reason for why this is so. :)

Another last minute update:

-- hash.lua
local newproxy = newproxy
local getmetatable = getmetatable
local next = next

module 'hash'

function new()
  local t={}
  local n=0
  local u=newproxy(true)
  local mt=getmetatable(u)
  mt.__index = function(o,k) return t[k] end
  mt.__newindex = function(o,k,v)
    if k~=nil then
      if t[k]==nil and v~=nil then -- new key?
        n=n+1
      elseif t[k]~=nil and v==nil then -- remove key?
        n=n-1
      end
      t[k]=v
    end
  end
  mt.__len = function(o) return n end
  mt.__hash = t
  return u
end

function pairs(h)
  return next, getmetatable(h).__hash, nil
end

Cheers,
Luis, needs to think more before posting. :)

-- 
A mathematician is a device for turning coffee into theorems.
        -- P. Erdos 

-- 
Luis Carvalho
Applied Math PhD Student - Brown University
PGP Key: E820854A <carvalho@dam.brown.edu>