Howdy, Stranger!

It looks like you're new here. If you want to get involved, click one of these buttons!

In this Discussion

custom __type metamethod

I want to make a metamethod in order to, for example, the type(Vector2(0,0)) was "Vector2D", not "table". To do this, I rewrote the type function from Lua

local _type = type
function type(v)
    local T = _type(v)
    if T == "table" then
        local tf = getmetatable(v).__type
        if _type(tf) == "function" then
            return tf(v)
        else
            return tostring(tf or T)
        end
    else
        return T
    end
end

But when I run the project, Codea crashes every time (the Problem disappears if i rewrite the type function inside the setup function). Why? How to fix this?

Tagged:

Comments

  • Posts: 15

    Okay, I see what the problem is. I haven't checked whether the table has metatable. Now everything works as it should

    rawtype = type
    function type(v)
        local T = rawtype(v)
        if T == "table" then
            local mt = getmetatable(v)
            if mt then --fix
                if rawtype(mt.__type) == "function" then
                    return mt.__type(v)
                elseif rawtype(mt.__type) == "string" then
                    return mt.__type
                end
            end
        end
        return T
    end
Sign In or Register to comment.