Type Of

lua-users home
wiki

玩一个 typeof() 操作符的概念。

当使用 module() 函数创建一个模块时,它会在 metatable._NAME 中添加一个模块名作为值。此函数利用了这种默认行为。注意:这不适用于 C 扩展,除非作者特意添加该值。

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
编辑 · 历史
最后编辑于 2006年3月1日 下午5:47 GMT (差异)