Question

I get the error 'attempt to call method 'Dot' (a nil value)' while running the following code:

-- 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)))

I'm not understanding what I've done wrong, could anyone lend a hand, I have good Lua experience, but have just started learning how to use metatables, so I'm new at this point, I am running it using SciTE, with LuaForWindows. Error is on the very last line, but the line above it runs perfectly

Was it helpful?

Solution

You have forgotten to set __index field:

Vector2 = {X = 0, Y = 0, Magnitude = 0, Unit = nil}
Vector2.__index = Vector2
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top