Using a coordinate pair as a key in a Lua table

怎甘沉沦 提交于 2021-01-03 06:29:07

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!