Nachtara
Nachtara

Reputation: 35

How do I enter or exit loops without completing them? (Lua)

I want to code a Mancala game for OpenComputers (minecraft mod), and it uses Lua. However, Mancala requires having to enter the main loop in the middle of it (six pots to choose from), exiting the loop in the middle (putting your last stone in an empty pot), and entering the loop from within the loop (putting last stone in a pot, have to pick up all stones from that pot).

I can easily do the mancalas on the sides, with a boolean for which player is going, and an if statement.

I have a quick flowchart to explain my problem, for those not familiar with Mancala: https://i.sstatic.net/2LA2m.jpg

One idea I had was something like this pseudocode:

declare pots1[0,4,4,4,4,4,4], pots2[0,4,4,4,4,4,4] //pots1[0] and pots2[0] are that player's mancala

function side1(pot,player) //pot is the pot chosen by the player
    declare stones = pots1[pot]
    pots1[pot] = 0

    do
        pot = pot + 1
        stones = stones - 1
        pots1[pot] = pots1[pot] + 1
    while stones > 0 and pot < 6

    if pot == 6 and stones > 0 and player //If stones were dropped in pot 6 and player1 is playing, drop stone in his mancala
        pots1[0] = pots1[0] + 1
        stones = stones - 1

    if stones == 0 //If player1 is out of stones, check the pot for more stones. Pick up all stones in pot and continue.
        if pots1[pot] > 1

I'm not sure where to go from here.

Upvotes: 0

Views: 418

Answers (2)

Kosho-b
Kosho-b

Reputation: 161

I'm not going to review the Mancala implementation, about exiting loop like 'break' logic,

you can do it in the old way:

function(stones, pot)    
    shouldIterate = true    
    while stones > 0 and shouldIterate do
        if pot == 6 then
            shouldIterate = false
        end
        pot = pot + 1
    end
end

Upvotes: 0

Paul Kulchenko
Paul Kulchenko

Reputation: 26744

The only way to exit and enter the loop as you are describing is to use yield and resume methods of Lua coroutines. coroutine.yield allows you to exit the current coroutine/function, but preserves its state exactly as is, so the subsequent coroutine.resume call will continue from the exact spot where yield was executed. yield can also return value(s) and resume can provide value(s), which allows to build more complex logic than just resume execution from a particular point.

You may want to check Chapter 9 in Programming in Lua for details on coroutines.

Upvotes: 1

Related Questions