Search code examples
lua

How to update/reload table key values


How can i update a key value using another key value as variable which is inside the same table?

local t = {}
t.playerPosition = {x = 0, y = 0, z = 0}
t.positions = {t.playerPosition.x + 1, t.playerPosition.y + 1, t.playerPosition.z + 1}

Then few lines later i update playerPosition

t.playerPosition = {x = 125, y = 50, z = 7}

And then if i print out...

result

t.positions[1] -- outputs 1
t.positions[2] -- outputs 1
t.positions[3] -- outputs 1

expected result

t.positions[1] -- outputs 126
t.positions[2] -- outputs 51
t.positions[3] -- outputs 8

As you can see key positions isnt updating, what could i do to make it possible?


Solution

  • t.positions = {t.playerPosition.x + 1, t.playerPosition.y + 1, t.playerPosition.z + 1}
    

    In the above line, the expressions are evaluated once, and the resulting values are assigned to fields of the subtable. After this point, changes to the fields of t.playerPosition will not cause a reflected change in t.positions.

    Metatables can be used to enable such behaviour, by dynamically calculating results when accessing the fields of t.positions.

    local t = {}
    t.playerPosition = { x = 0, y = 0, z = 0 }
    t.positions = setmetatable({}, {
            __newindex = function () return false end,
            __index = function (_, index)
                local lookup = { 'x', 'y', 'z' }
                local value = t.playerPosition[lookup[index]]
    
                if value then
                    return value + 1
                end
            end
    })
    
    print(t.positions[1], t.positions[2], t.positions[3])
    t.playerPosition = {x = 125, y = 50, z = 7}
    print(t.positions[1], t.positions[2], t.positions[3])