Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
471 views
in Technique[技术] by (71.8m points)

love2d - plese help me to solve Error main.lua:50: attempt to index global 'coin' (a nil value)

how do i use the Table coin in the function love.graphic.rettangle without making it global? I declare the table in a love.update() function (I don't know if anything changes)

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

question from:https://stackoverflow.com/questions/65835984/plese-help-me-to-solve-error-main-lua50-attempt-to-index-global-coin-a-nil

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
for i=1, #coins, 1 do
   love.graphics.rectangle("fill", coin.x, coin.y, coin.w, coin.w, coin.h)
 end

In the scope of your function love.draw, coin is a nil value.

coin is local to the followin if statement and hence cannot be used outside.

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

But as you inserted the local coin into coins you can access each coin by indexing coins if draw.love is in its scope.

So instead of the for loop above write

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

As coins is a sequence you could also use a generic for loop with ipairs

You probably have a coin.w to many btw.

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...