1

我试图通过连接场地的相对边缘来创建一个无限的游戏场地。我收到以下错误:

错误:试图索引字段“?” (零值)

错误以粗体显示。据我了解,在函数 drawField() 中调用数组字段时不包含任何值,尽管它在函数 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

-- Program Loop
clearField()
while true do
  local lastEvent = {event.pullFiltered(filter)}
  if lastEvent[1] == "touch" and lastEvent[5] == 0 then
    --State invertion
    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

显示事件变量是库。该程序以displayWidth = 160 和displayHeight = 50运行

4

1 回答 1

0

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

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

您可以实现一个 __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-30T08:18:49.453 回答