将一个坐标对作为Lua表中的键。

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

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。

点赞
用户1442917
用户1442917

我认为你的方法很好。在coord2index函数中,你也可以使用字符串代替数字,并做出类似于return x..';'..y的操作。

2015-01-16 02:53:54