Type Of

lua-users home
wiki

Playing around with the concept of a typeof() operator.

When a module is made using the module() function, it adds a value of the module name as metatable._NAME. This function takes advantage of that default behavior. Note: this doesn't apply to C extensions, unless the author specifically adds the value.

function typeof(var)
    local _type = type(var);
    if(_type ~= "table" and _type ~= "userdata") then
        return _type;
    end
    local _meta = getmetatable(var);
    if(_meta ~= nil and _meta._NAME ~= nil) then
        return _meta._NAME;
    else
        return _type;
    end
end
    

RecentChanges · preferences
edit · history
Last edited March 1, 2006 11:47 pm GMT (diff)