Search code examples
lua

I can't understand the error and how to fix it. Lua version 5.1


I can’t figure it out, the error is on line 36. How to fix it and why does it occur? What am I doing wrong?

Runtime Error at line: -1: d:\gameobject.lua:36: attempt to call method 'position' (a table value)

Vector3f = {}
Vector3f.__index = Vector3f

function Vector3f:new(x, y, z)
    local vector = {x = x or 0, y = y or 0, z = z or 0}
    setmetatable(vector, self)
    return vector
end

Transform = {}
Transform.__index = Transform

function Transform:new(position, rotation, scale)
    local transform = {
        position = position or Vector3f:new(0, 0, 0),
        rotation = rotation or Vector3f:new(0, 0, 0),
        scale = scale or Vector3f:new(0, 0, 0)
    }
    setmetatable(transform, self)
    return transform
end

function Transform:position(x, y, z)
    self.position.x = x or self.position.x
    self.position.y = y or self.position.y
    self.position.z = z or self.position.z
end

local pos = Vector3f:new(1, 2, 3)
local rot = Vector3f:new(4, 5, 6)
local sca = Vector3f:new(7, 8, 9)

local transform = Transform:new(pos, rot, sca)
print("X: " .. transform.position.x .. " Y: " .. transform.position.y .. " Z: " .. transform.position.z)
print("X: " .. transform.rotation.x .. " Y: " .. transform.rotation.y .. " Z: " .. transform.rotation.z)
print("X: " .. transform.scale.x .. " Y: " .. transform.scale.y .. " Z: " .. transform.scale.z)

transform:position(10, 20, 30)
print("X: " .. transform.position.x .. " Y: " .. transform.position.y .. " Z: " .. transform.position.z)

Solution

  • You named both a property and a function position. You can't do that. functions are also properties and as soon as you give the transform instance a position property your overwrote the function that was there. You should simply name them differently. So for example change

    function Transform:position(x, y, z)
    

    to

    function Transform:setPosition(x, y, z)
    

    and change

    transform:position(10, 20, 30)
    

    to

    transform:setPosition(10, 20, 30)