【发布时间】:2015-03-14 14:51:30
【问题描述】:
正如标题所说,我正在尝试使用坐标对 (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] = 5 和print(test[1,1])。这没有技术上的需要,纯粹是为了我对 Lua 的进一步熏陶。
【问题讨论】: