【问题标题】:plese help me to solve Error main.lua:50: attempt to index global 'coin' (a nil value)请帮我解决错误 main.lua:50:尝试索引全局“硬币”(零值)
【发布时间】:2021-04-26 09:05:26
【问题描述】:

如何在函数 love.graphic.rettangle 中使用 Table 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

【问题讨论】:

  • 你写的是coin而不是coins[i]
  • 如果您发布带有行号的错误消息,请从头发布代码或添加注释告诉大家哪一行是第50行。这样我们就不必通读所有你的代码。这就是错误消息带有行号的原因。这样您就知道在哪里寻找错误原因。

标签: lua love2d


【解决方案1】:
for i=1, #coins, 1 do
   love.graphics.rectangle("fill", coin.x, coin.y, coin.w, coin.w, coin.h)
 end

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

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 中时,如果 draw.love 在其范围内,您可以通过索引 coins 来访问每个硬币。

所以不要写上面的for循环

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

由于硬币是一个序列,您还可以使用带有 ipairs 的通用 for 循环

顺便说一句,您可能有一个coin.w

for _, coin in ipairs(coins) do
  love.graphics.rectangle("fill", coin.x, coin.y, coin.w, coin.h)
end

【讨论】:

    猜你喜欢
    • 2013-08-29
    • 2020-11-03
    • 2017-04-08
    • 2020-10-30
    • 1970-01-01
    • 1970-01-01
    • 2015-02-18
    • 2020-04-27
    相关资源
    最近更新 更多