正如标题所说,我正在尝试将坐标对(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。
test["1,2"] = 5
和print(test["1,2"])
的操作吗?或者我是愚钝了,错过了什么? - Timbermartest[a..';'..b]
,但这会向用户公开实现细节。在您的实现中,您已隐藏了这些细节,这就是我建议使用相同机制的原因,只是键的格式不同。 - Paul Kulchenkox..';'..y
这段代码依赖于数字类型(整数/浮点数),并且很难追踪这种类型。例如,旧的 C 代码可能使用lua_pushnumber
将坐标传递给 Lua,而其他部分则使用数字字面量。我认为如果坐标是整数,则代码应该使用 floor/ceil/round 或使用 string.format("%g;%g",...) 来确保数字是整数。 - moteus