Jump to content

Lua/Loops

From Wikiversity
< Lua

Lua modules based on the Scribunto/Lua extension are stored in resource pages using the Module: namespace. Each module uses a table to hold functions and variables, and that containing table is returned at the end of the module code.[1] Loops are code structures used to repeat statements in scripts. This lesson will show you how to use loops in your scripts.

Prerequisites

[edit | edit source]

This lesson assumes you have already completed the Conditions lesson.

Create a Lua Script with Loops

[edit | edit source]

To create a Lua script with loops:

  1. In Module:Sandbox, click Edit source.
  2. Replace existing code pasting the following code without clicking Publish changes.

New Lua forLoop Script

[edit | edit source]
local p = {} -- the only variable with one single letter
function p.forLoop() -- count from 2 to 10 increment 2
    local ind; local from = 2; local to = 10; local step = 2
    local result = ';for\n:ind = '
    for ind = from, to, step do -- After `, to`: add `, step` only if step > 1
        result = result .. ind -- concatenate the string result with each index
        if ind < to then result = result .. ', ' end -- add comma
    end
    return result
end
return p

To test your Lua script:

  1. Scroll down until Debug console at the end of the page.
  2. Paste the following call and validate by Enter: ↲
print(p.forLoop())

The result should be displayed in one second:

;for
:ind = 2, 4, 6, 8, 10

New whileLoop Script

[edit | edit source]
local p = {}
function p.whileLoop()
    local ind = 2; local to = 10; local step = 2
    local result = ';while\n:ind = '
    while ind <= to do -- tests before the body
        result = result .. ind
        if ind < to then result = result .. ', ' end
        ind = ind + step -- CAUTION: never forgets to increment to avoid infinite waiting
    end
    return result
end
return p

In Debug console:

  1. Paste the following call and validate by Enter: ↲
print(p.whileLoop())

The output is the same except for the semicolon heading:

;while
:ind = 2, 4, 6, 8, 10

New Lua repeatLoop Script

[edit | edit source]
--[[WARNING about infinite loop]]--
-- The main issue of loop is the infinite waiting if step is 0 or the condition in until is never True.
-- If the loop is infinite because of a bug, try to click Cancel, close Module:Sandbox or the browser.
local p = {}
function p.repeatLoop()
    local ind = 2; local to = 10; local step = 2 -- should be never 0
    local result = ';repeat\n:ind = '
    repeat 
        result = result .. ind
        if ind < to then result = result .. ', ' end
        ind = ind + step  -- CAUTION: be sure to increment with a positive value >= 1
    until ind > to -- tests after the body. Feel free to add any watchdog in real case.
    return result
end
return p

In Debug console:

print(p.repeatLoop())
;repeat
:ind = 2, 4, 6, 8, 10

Test Your Lua Script

[edit | edit source]

To test your Lua script:

  1. Save the Module:Sandbox to call it from another Wiki page.
  2. Navigate to either the Module_talk:Sandbox page, the Wikiversity:Sandbox page, or your own user or sandbox page.
  3. Add the following code and save the page:
{{#invoke:Sandbox|repeatloop}}

The result should be:

repeat
ind = 2, 4, 6, 8, 10

Understand Your Lua Script

[edit | edit source]

Understand forLoop Script

[edit | edit source]

To understand your Lua script for loop:

  1. local and the following code defines the variables ind and result.
  2. result = ';for\n:ind = ' assigns a string literal value to the variable result.
    This could also have been written with the initial variable declaration as local result = ';for\n:ind = '. There is no difference in functionality, only in the author's preference for coding style. Some programming languages require variables to be declared before they are used, resulting in some developers preferring to see variables declared before they are used.
  3. for ind = 2, 10, 2 do creates a loop code block that will vary the value of the variable ind from 2 to 10 by 2.
    • For loops are used when the number of loops desired can be easily determined before the loop is entered. They are typically counting loops of some type.
    • For loops can be sequenced either in a positive or a negative direction. for ind = 10, 2, -2 do would count down from 10 to 2 by 2.
    • If the increment value is not provided, the default increment is 1. for ind = 1, 10 do would count from 1 to 10 by 1.
  4. result = result .. ind concatenates a string literal and the current value of the variable ind to result.
  5. end ends the loop.
    The value of the loop variable, ind in this case, will be one increment greater than the stop value when the loop ends. In this example, ind will be equal to 12 after the loop ends.
  6. return result returns the current value of result as the result of the function.

Understand whileLoop Script

[edit | edit source]

To understand your Lua script while loop:

  1. local and the following code defines the variables ind and result.
  2. result = ';while\n:ind = ' assigns a string literal value to the variable result.
  3. ind = 2 assigns the value 2 to the variable ind.
    This could also have been written with the initial variable declaration as local ind = 2.
  4. while ind <= 10 do creates a loop code block that will loop while the value of ind is less than 10.
    • While loops are used when the number of loops desired is determined within the loop, such as repeating until the end of a string is reached. A while loop is used here to demonstrate the comparison in code structure between for, while, and repeat loops.
    • If the while loop condition is not met, the loop code block will be skipped.
    • If the while loop condition is met, the while loop condition must be altered inside the loop, or the loop will repeat forever.
  5. result = result .. ind concatenates a string literal and the current value of the variable ind to result.
  6. ind = ind + 2 takes the current value of ind, adds 2, and stores the result in ind.
  7. end ends the loop.
  8. return result returns the current value of result as the result of the function.

Understand repeatLoop Script

[edit | edit source]

To understand your Lua script repeat loop:

  1. local and the following code defines the variables ind and result.
  2. ind = 2 assigns the value 2 to the variable ind.
  3. result = ';repeat\n:ind = ' assigns a string literal value to the variable result.
  4. repeat creates a loop code block that will loop until the ending condition is true.
    • Repeat loops are used when the number of loops desired is determined within the loop, such as repeating until the end of a string is reached.
    • The difference between a while loop and a repeat loop is that the while loop may not execute if the condition is not met. A repeat loop always executes at least once.
    • If the repeat loop condition is met, the repeat loop condition must be altered inside the loop, or the loop will repeat forever.
  5. result = result .. ind concatenates a string literal and the current value of the variable ind to result.
  6. ind = ind + 2 takes the current value of ind, adds 2, and stores the result in ind.
  7. until ind > 10 sets the condition that is tested to end the loop. If the condition is false, the loop repeats. If the condition is true, the loop terminates.
  8. return result returns the current value of result as the result of the function.

Conclusion

[edit | edit source]

Congratulations! You've now created, tested, and understood a Lua script with loops. Continue on to the Functions lesson.

See Also

[edit | edit source]

References

[edit | edit source]
  1. "Extension:Scribunto/Lua reference manual". Mediawiki. 2026. Retrieved 2026-04-05.