问题
As the title says, I'm trying to use a coordinate pair (x, y) as a key for a table. Here is what I have done so far
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}])
This is actually working as expected. What I'm really wondering if there is a way to reduce this even more, something like test[1,2] = 5
and print(test[1,1])
. There is no technical need for this, it's purely for my further edification into Lua.
回答1:
I think your method is good. You can also use strings instead of numbers and do something like return x..';'..y
in your coord2index
function.
来源:https://stackoverflow.com/questions/27976526/using-a-coordinate-pair-as-a-key-in-a-lua-table