使用Metatable的方法尝试调用方法(零值)时出错

时间:2013-07-21 14:32:30

标签: lua metatable

运行以下代码时出现错误'尝试调用方法'Dot'(零值):

-- Vector2 Class
Vector2 = {X = 0, Y = 0, Magnitude = 0, Unit = nil}
function Vector2.new(XValue,YValue)
    local Tmp = {}
    setmetatable(Tmp,Vector2)
    Tmp.X = XValue
    Tmp.Y = YValue

    Tmp.Magnitude = math.sqrt(Tmp.X * Tmp.X + Tmp.Y * Tmp.Y)
    if Tmp.Magnitude ~= 1 then
        Tmp.Unit = Tmp/Tmp.Magnitude
    else
        Tmp.Unit = Tmp
    end

    return Tmp
end

-- Arithmetic
function Vector2.__add(A,B)
    if getmetatable(A) == getmetatable(B) then
        return Vector2.new(A.X+B.X, A.Y+B.Y)
    end
end

function Vector2.__sub(A,B)
    if getmetatable(A) == getmetatable(B) then
        return Vector2.new(A.X-B.X, A.Y-B.Y)
    end
end

function Vector2.__mul(A,B)
    if tonumber(B) ~= nil then
        return Vector2.new(A.X*B, A.Y*B)
    end
end

function Vector2.__div(A,B)
    if tonumber(B) ~= nil then
        return Vector2.new(A.X/B, A.Y/B)
    end
end

function Vector2.__unm(Tmp)
    return Vector2.new(-Tmp.X, -Tmp.Y)
end

-- Comparisons
function Vector2.__eq(A,B)
    if getmetatable(A) == getmetatable(B) then
        if A.X == B.X and A.Y == B.Y then
            return true
        else
            return false
        end
    end
end

function Vector2.__lt(A,B)
    if getmetatable(A) == getmetatable(B) then
        if A.Magnitude < B.Magnitude then
            return true
        else
            return false
        end
    end
end

function Vector2.__le(A,B)
    if getmetatable(A) == getmetatable(B) then
        if A.Magnitude <= B.Magnitude then
            return true
        else
            return false
        end
    end
end

-- Functionals
function Vector2.__tostring(Tmp)
    return Tmp.X..", "..Tmp.Y
end

function Vector2:Dot(B)
    return self.X*B.X + self.Y*B.Y
end

function Vector2:Lerp(B,Amn)
    return self + (B-self)*Amn
end

print(Vector2.new(1,0.3).Magnitude)
print(Vector2.new(1,0):Dot(Vector2.new(0,1)))

我不明白我做错了什么,有没有人伸出援手,我有很好的Lua经验,但刚刚开始学习如何使用metatables,所以我现在是新的,我正在运行它使用SciTE和LuaForWindows。错误在最后一行,但它上面的行完美运行

1 个答案:

答案 0 :(得分:1)

您忘记设置__index字段:

Vector2 = {X = 0, Y = 0, Magnitude = 0, Unit = nil}
Vector2.__index = Vector2