Search code examples
lualove2d

Is there an equivalent for the "goto" loop in C# in lua? (Must be compatible with Love2D)


I'm currently coding a game for a school project, a sort of Space Invader type of game. I'm currently trying to make a screen where it says "Press R to restart" so that when the player presses R the games goes back to the start. Like in C# exemple : Start: (all your code) goto Start. So my question is there an equivalent of this? I cannot find something about that on the internet.

I've already tried the return loop but it crashes the game before it even starts. I saw that Lua actually has a goto loop in the 5.2 version. But Love2D only supports Lua 5.1 so now I've tried repeat ... until (condition) but it still doesn't work

Beginning of the code :

repeat

score = 0
enemykills = 0
local start = love.timer.step( )

End of the code :

    love.graphics.setColor(255, 255, 255)
    for _,b in pairs(player.bullets) do
      love.graphics.rectangle("fill", b.x, b.y, 2, 2)
    end
end
until not love.keyboard.isDown("r")

I want the game to restart when I press R but it either crashes or does nothing.


Solution

  • Love2D will call your love.update and love.draw functions repeatedly. You don't need to have such a loop. What you need to do is remember that your game is in the "wait for user to press 'r' to restart" state. So your code would look something like this:

    local current_state = "normal"
    
    function love.update(dt)
        if(current_state == "wait") then
            if(love.keyboard.isDown("r")) then
                current_state == "normal"
            end
        else
            --[[Do normal processing]]
        end
    end