读取二维表时出错

我正在尝试通过连接场地的相反边缘来创建无限游戏场地。我得到了以下错误:

错误:尝试索引字段“?”(一个算值)

错误发生在粗体字的行上。据我所知,在函数“drawField()”中调用数组_field_时,尽管通过函数“clearField()”将其填充为零,但该数组不包含任何值。如何修复数组,使其在“clearField()”外保留其值?

local black = 0x000000
local white = 0xFFFFFF

local field = {}
local function clearField()
  for gx=1,displayWidth do
    if gx==displayWidth then
      field[1] = field[displayWidth+1]
    end
    field[gx] = {}
    for gy=1,displayHeight-3 do
      if gy==displayHeight-3 then
        field[gx][1] = field[gx][displayHeight-2]
      end
      field[gx][gy] = 0
    end
  end
end

--Field redraw
local function drawField()
  for x=1, #field do
    for y=1,x do
      **if field[x][y]==1 then**
        display.setBackground(white)
        display.setForeground(black)
      else
        display.setBackground(black)
        display.setForeground(white)
      end
      display.fill(x, y, 1, 1, " ")
    end
  end
end

-- 程序循环
clearField()
while true do
  local lastEvent = {event.pullFiltered(filter)}
  if lastEvent[1] == "touch" and lastEvent[5] == 0 then
    --状态反转
    if field[lastEvent[3]][lastEvent[4]]==1 then
      field[lastEvent[3]][lastEvent[4]] = 0
    else
      field[lastEvent[3]][lastEvent[4]] = 1
    end
    drawField()
  end
end

displayevent 变量是库。 该程序的 displayWidth = 160,displayHeight = 50。

点赞
用户2858170
用户2858170

field[1] = field[displayWidth+1]等同于field[1] = nil,因为你从未将值分配给field[displayWidth+1]

运行以下代码来验证:

clearField()
print(field[1])
for k,v in pairs(field) do print(v[1]) end

因此,在外部循环中,您为field创建了10个条目,但在第10次运行时删除了field[1],这后来导致观察到的错误,因为您正在尝试在if field[x][y]==1 then中索引field[1]

您可以实现一个__index元方法来获得“略微”循环数组。例如:

local a = {1,2,3,4}
setmetatable(a, {
  __index = function(t,i)
    local index = i%4
    index = index == 0 and 4 or index
    return t[index] end
})
for i = 1, 20 do print(a[i]) end
2020-07-30 08:18:49