lua-users home
lua-l archive

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


> If there were a metamethod called when a table element is deleted (set to
> nil) you could do without the proxy table here (and in many other
> situations).
> 
> Having a __removeindex metamethod is something *I* would like in 5.2 :)

I had to use the proxy userdata to override __len, since you can't set __len
for tables. Otherwise, you could get away with just

function newhash()
  local n = 0
  return setmetatable({}, {
    __index = function(o,k) return rawget(o,k) end,
    __newindex = function(o,k,v)
      if rawget(o,k)==nil then n=n+1 elseif v==nil then n=n-1 end
      rawset(o,k,v)
    end,
    __len = function(o) return n end
  })
end

But

Lua 5.1  Copyright (C) 1994-2006 Lua.org, PUC-Rio
> require'hash'
> h=newhash()
> h.k1=10
> h.k2=20
> = #h
0
> = debug.getupvalue(getmetatable(h).__newindex, 1)
n       2

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).

Cheers,
Luis.

-- 
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>