lua-users home
lua-l archive

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



I don't think there's a way of obtaining the hash (or
address) of a string from plain Lua

There is a way to get the pointer of a object with plain lua using the %p format modifier as in:

local function obj_hash(obj)
    return tonumber(string.format("%p", obj))
end


a different method would be to use a weak table to store hash values:

local NEXT_HASH, HASHES = 1, setmetatable({}, {__mode="k"})

local function obj_hash(obj)
    local hash = HASHES[obj]
    if not hash then
        hash = NEXT_HASH
        HASHES[obj], NEXT_HASH = hash, hash + 1
    end
    return hash
end

Note that both methods only work for objects. Nil, numbers and boolean need special treatment.

Regards,
Xmilia