使用坐标对作为 Lua table 中的键

Using a coordinate pair as a key in a Lua table

正如标题所说,我正在尝试使用坐标对 (x, y) 作为 table 的键。这是我到目前为止所做的

local test = {_props = {}}
local mt = {}
local xMax = 5
local yMax = 5

local function coord2index(x, y)
    return ((x-1) * xMax) + y
end

mt.__index = function(s, k)
    if s._props[coord2index(k[1], k[2])] ~= nil then
        return s._props[coord2index(k[1], k[2])]
    end
end

mt.__newindex = function(s, k, v)
   s._props[coord2index(k[1], k[2])] = v 
end
mt.__call = function (t, k)
    if type(k) == "table" then print "Table" end
end

setmetatable(test, mt)

test[{1,2}] = 5
print( test[{1,2}])

这实际上按预期工作。我真的很想知道是否有办法进一步减少它,比如 test[1,2] = 5print(test[1,1])。这个没有技术上的需要,纯粹是为了进一步熏陶我Lua.

我觉得你的方法很好。您还可以使用字符串而不是数字,并在 coord2index 函数中执行类似 return x..';'..y 的操作。