我试图通过连接字段的相反边缘来创建一个无限的游戏场。我得到以下错误:
错误:尝试索引字段“?”(a零值)
错误出现在粗体线上。据我所知,数组字段在函数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运行。
发布于 2020-07-30 08:18:49
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],这将导致在if field[x][y]==1 then中尝试inxex field1时所观察到的错误
您可以实现一个__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]) endhttps://stackoverflow.com/questions/63168271
复制相似问题