Programming Fundamentals/Loops/Lua

loops.lua

edit
-- This program demonstrates While, Do, and For loop counting using
-- user-designated start, stop, and increment values.
--
-- References:
--     https://www.lua.org/manual/5.1/manual.html

function get_value(name)
    local value
    
    io.write("Enter ", name, " value:", "\n")
    value = tonumber(io.read())
    
    return value
end

function while_loop(start, stop, increment)
    io.write("While loop counting from ", start, " to ", stop, 
        " by ", increment, ":", "\n")
    local count
    
    count = start
    while count <= stop do
        io.write(count, "\n")
        count = count + increment
    end
end

function do_loop(start, stop, increment)
    io.write("Do loop counting from ", start, " to ", stop, 
        " by ", increment, ":", "\n")
    local count
    
    count = start
    repeat
        io.write(count, "\n")
        count = count + increment
    until not (count <= stop)
end

function for_loop(start, stop, increment)
    io.write("For loop counting from ", start, " to ", stop, 
        " by ", increment, ":", "\n")
    local count
    
    for count = start, stop, increment do
        io.write(count, "\n")
    end
end

function main()
    local start
    local stop
    local increment

    start = get_value("starting")
    stop = get_value("ending")
    increment = get_value("increment")

    while_loop (start, stop, increment)
    do_loop (start, stop, increment)
    for_loop (start, stop, increment)
end

main()

Try It

edit

Copy and paste the code above into one of the following free online development environments or use your own Lua compiler / interpreter / IDE.

See Also

edit