lua-users home
lua-l archive

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


Colin wrote:
> However I don't see how to implement such a __hash meta method in
> Lua; this idea is geared towards my currently problematic use case: C
> __hash methods for userdata objects.  

You can use index and newindex metamethods to achieve that result. Example (not tested):

local t = {}

function index(t, k)
    if type(k)=='userdata' then
        local mt = getmetatable(k)
        if mt and mt.__hash then
            k = mt.__hash(k)
        end
    end
    return t[k]
end

function newindex(t, k, v)
    if type(k)=='userdata' then
        local mt = getmetatable(k)
        if mt and mt.__hash then
            k = mt.__hash(k)
        end
    end
    t[k] = v
end

setmetatable(t, {__index=index, __newindex=newindex})

Here the hash metamethod takes the userdata, and returns a hashvalue. If two userdata return the same hashvalue they will be put in the same table slot. You can even use pairs to iterate on the values (but the keys returned by pairs won't be the original userdata but their hash).