lua-users home
lua-l archive

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


> So realistically, if you want (non-mutable) userdata to be equivalent in
> the sense of builtin object types, you need to implement some kind of
> weak-reference system to avoid creating new userdata if an equivalent
> one exists already, in which case you don't need to implement the eq
> metamethod anymore, since they will BE the same userdata if they
> satisfy "equivalency" rules.

I don't know exactly what you mean, but you can certainly have types as
userdata stored in a weak-valued table indexed by type name as the equivalence
relation, say, and, to answer your question in the subject, objects as
userdata that are different "table keys", but still equivalent if they are of
the same type by the __eq metamethod. For example:

do
  local tbuf = setmetatable({}, {__mode = "v"})
  newtype = function(name)
    local t = tbuf[name]
    if not t then
      t = newproxy(true)
      getmetatable(t).__eq = function() return true end
      tbuf[name] = t
    end
    return t
  end
end

newobject = function(typ)
  return newproxy(typ)
end

Lua 5.1.1  Copyright (C) 1994-2006 Lua.org, PUC-Rio
> t1 = newtype"t1"
> x = newobject(t1)
> y = newobject(t1)
> = x
userdata: 0x3072a4
> = y
userdata: 0x3074d4
> = x==y -- diff objects, same type
true
> t2 = newtype"t2"
> x2 = newobject(t2)
> y2 = newobject(t2)
> = x2==y2 -- same type
true
> = x1==y2 -- diff types
false

I hope this helps. :)

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>