user2894128
user2894128

Reputation:

Lua problem with variables being referenced

I have this in main.lua:

local Vector3 = require "vector3"

local A = {
    v = Vector3:new(16,16,16)
}

b = Vector3:new(A.v.x + 2, A.v.y + 3, A.v.z + 4)
print(A.v.x)

and this in Vector3.lua

local Vector3 = {
    x,
    y,
    z
}

function Vector3:new(x,y,z)
    o = {}
    setmetatable(o,self)
    self.__index = self

    self.x = x
    self.y = y
    self.z = z

    return o
end

return Vector3

Why does it print 18 instead of 16? I guess it has something to do with the variables being referenced. How can I get 16 as result?

Upvotes: 1

Views: 125

Answers (1)

lhf
lhf

Reputation: 72312

Vector3:new is setting fields in Vector3, not in the object created. Try this:

function Vector3:new(x,y,z)
    local o = {}
    setmetatable(o,self)
    self.__index = self
    o.x = x
    o.y = y
    o.z = z
    return o
end

Upvotes: 3

Related Questions