如何 update/reload table 键值

How to update/reload table key values

如何使用同一 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}

然后几行之后我更新 playerPosition

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

然后如果我打印出来...

结果

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

预期结果

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

如您所见,键 positions 没有更新,我该怎么做才能让它成为可能?

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

在上面的行中,表达式被计算一次,并将结果值分配给子表的字段。在此之后,对 t.playerPosition 字段的更改不会导致 t.positions 中的反映更改。

Metatables 可用于启用此类行为,方法是在访问 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])