luacomputercraft

How do i set variable after repeat until loop?


i've got a query about my code. I currently cant test it so i thought i'd ask. (for context i'm very new to lua) Hopefully i'm not asking a duplicate question, or anything similar.

here's my code currently

write("Column: ")
local column = tonumber( read() )
write("Row: ")
local row = tonumber( read() )
local x = 0
local y = 0

function digforward(str)
    repeat
        turtle.dig()
        turtle.forward()
        x = x+1
    until x == column

So after the repeat until loop ends, what would i do to set the variable x back to 0? I'm aware that x = 0 would normally do it, but i want to make it so when you run the function it goes till x = column and then set x to 0.

Additionally just so you know this is code for a computer in a game. (from the computercraft mod for minecraft)


Solution

  • In that case, it'd be better to just use a numeric for-loop:

    for x = 1, column do
       turtle.dig()
       turtle.forward()
    end
    

    And as a small extra:

    for x = 1, column do
       while not turtle.forward() do
          turtle.dig()
       end
    end
    

    This makes sure to re-try until the turtle actually manages to move, like when a sand block falls down immediately after digging. You can also throw in an attack for good measure for cases when an enemy is blocking the movement.