请帮我解决 Error main.lua:50: attempt to index global 'coin' (a nil value)

如何在 love.graphic.rettangle 函数中使用表格 coin 而不使其成为全局变量?我在 love.update() 函数中声明了表格(我不知道是否有任何变化)

if math.random() < 0.01 then --math.rand restituisce numeri da 0 a 1 (la usiamo come probabilità)
 local coin = {}
     coin.h = 80
     coin.w = 80
     coin.x = math.random(0, 800 - coin.w)
     coin.y = math.random(0, 800 - coin.h)
         table.insert(coins, coin)-- inseriamo nella table coins il table coin appena creato
 end
end
function love.draw()
--[[love.graphics.setBackgroundColor( 255, 150, 150)
love.graphics.setColor(255, 0, 0)]]
love.graphics.setColor(255, 0, 0)
love.graphics.rectangle("fill", player.x, player.y, player.w, player.h)
love.graphics.setColor(255, 255, 0)
 for i=1, #coins, 1 do
   love.graphics.rectangle("fill", coin.x, coin.y, coin.w, coin.w, coin.h)
 end
end
点赞
用户2858170
用户2858170

在你的函数 love.draw 的范围内,coin 是一个空值。

coin 是局部变量,限于以下的 if 语句,因此不能在外部使用。

if math.random() < 0.01 then --math.rand restituisce numeri da 0 a 1 (la usiamo come probabilità)
 local coin = {}
     coin.h = 80
     coin.w = 80
     coin.x = math.random(0, 800 - coin.w)
     coin.y = math.random(0, 800 - coin.h)
         table.insert(coins, coin)-- inseriamo nella table coins il table coin appena creato
 end

但是由于你将局部变量 coin 插入到了 coins 中,如果在 love.draw 的范围内,你可以通过对 coins 索引来访问每个硬币。

因此,不需要上面的循环,可以写成如下部分:

for i=1, #coins, 1 do  -- the third parameter defaults to 1 so for i = #coins do is enough
   local coin = coins[i]
   love.graphics.rectangle("fill", coin.x, coin.y, coin.w, coin.w, coin.h)
 end

由于 coins 是一个序列,你可以使用 ipairs 泛型循环来遍历。

注意,你可能多了一个 coin.w

for _, coin in ipairs(coins) do
  love.graphics.rectangle("fill", coin.x, coin.y, coin.w, coin.h)
end
2021-01-22 08:50:22