【发布时间】:2013-03-19 00:28:20
【问题描述】:
我有时在 Lua 中制作小游戏,并且经常需要将 2D 数组实现为网格或棋盘。当我想检查特定单元格周围的单元格时,我通常给二维数组一个元表,这样当 grid[outOfBoundsNum] 被索引时,它会返回一个空表而不是错误:
setmetatable(grid, {
__index =
function(t, key)
if not table[key] then
return {}
else
return table[key]
end
end})
所以当grid[outOfBoundsNum][anything]被调用时,它会返回nil。然后,要检查周围的细胞,我会这样做:
for k, v in ipairs(neighbours) do
local cell = grid[v[1][v[2]]
if cell then -- check if this is actually within the 2D array
if cell == 1 then
-- do something
elseif cell == 2 then
-- do something else
...
end
end
这行得通,但对我来说似乎很尴尬。有没有更好或更好的方法?
【问题讨论】:
-
为什么
neighbours包含{{x1, y1}, {x2, y2}, ...}而不是{cell1, cell2, ...}? -
没有理由,这只是一个例子。我写的模块其实用的是第二种方法{cell1, cell2, ...}