Lua/Conditions

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. Conditions are code structures used to make choices and control the flow of scripts. This lesson will show you how to use conditions in your scripts.

Prerequisites
This lesson assumes you have already completed the Expressions lesson.

Create a Lua Script with Conditions
To create a Lua script with conditions: ""
 * 1) Navigate to Module:Sandbox.
 * 2) Clear all existing code.
 * It's a sandbox. Everyone is free to play in the sandbox.  But if you find another user is actively editing the sandbox at the same time, you may also use Module:Sandbox/Username, where Username is your Wikiversity username.
 * 1) Add the following code and save the page:

Test Your Lua Script
To test your Lua script:
 * 1) Navigate to either the Module_talk:Sandbox page, the Sandbox page, or your own user or sandbox page.
 * 2) Add the following code and save the page:

The result should be either: "Good morning!" or "Good afternoon!" or "Good evening!" depending on the UTC time of day.

Understand Your Lua Script
To understand your Lua script:
 * 1)   and the following code defines the variables   and  .  Both are.
 * 2)   returns the current server time formatted in hours (%H) from 0 to 23 as a string.  Server time is typically set to UTC rather than local time.
 * 3)   converts the string to a number.
 * 4)   stores the numeric value of the server time in the variable.
 * 5)   begins a conditional code block and checks   to see if it is less than  .  If it is, the following statement(s) are executed.  If not, the following statements are skipped.
 * 6)   sets the value of result.
 * 7)   checks   to see if it is less than  .  If it is, the following statements are executed.  If not, the following statements are skipped.
 * 8) *Conditions are mutually exclusive. If the first condition was true (if), the second condition (elseif) is not evaluated.
 * 9) * is optional in a conditional code block and may be repeated.
 * 10)   indicates that if none of the previous conditions were true, the following statements are executed.  If one of the previous statements was true, the following statements are skipped.
 * is optional in a conditional code block.
 * 1)   ends the conditional code block.
 * 2)   returns the current value of result as the result of the function.

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