1

运行以下代码时出现错误“尝试调用方法 '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 经验,但刚刚开始学习如何使用元表,所以我现在是新手,我正在使用 SciTE 运行它,使用 LuaForWindows。错误在最后一行,但它上面的行完美运行

4

1 回答 1

1

您忘记设置__index字段:

Vector2 = {X = 0, Y = 0, Magnitude = 0, Unit = nil}
Vector2.__index = Vector2
于 2013-07-21T14:49:14.633 回答