在Lua表中使用坐标对作为键 [英] Using a coordinate pair as a key in a Lua table

查看:58
本文介绍了在Lua表中使用坐标对作为键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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}])

这实际上按预期工作.我真正想知道的是是否有办法进一步减少这种情况,例如 test [1,2] = 5 print(test [1,1]).对此没有技术上的需求,这完全是为了进一步教育Lua.

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.

推荐答案

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

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.

这篇关于在Lua表中使用坐标对作为键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆