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.[1] 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
[edit | edit source]This lesson assumes you have already completed the Expressions lesson.
Create a Lua Script with Conditions
[edit | edit source]To create a Lua script with conditions:
- In Module:Sandbox, click
Edit source. - Replace existing code pasting the following code without clicking
Publish changes.
local p = {} function p.conditions() -- Greetings according to the hour local hour = tonumber(os.date('%H')) -- Get current Hour if hour < 12 then return 'Good morning!' elseif hour < 18 then return 'Good afternoon!' else return 'Good evening!' end end return p
Debug Your Lua Script
[edit | edit source]To test your Lua script:
- Scroll down until
Debug consoleat the end of the page. - Paste the following call and validate by Enter: ↲
print(p.conditions())
The result should be either:
Good morning!
or
Good afternoon!
or
Good evening!
depending on the UTC time of day.
Click Cancel. "Leave site?" Click Leave. Close Module:Sandbox.
Understand Your Lua Script
[edit | edit source]To understand your Lua script:
localand the following code defines the variablehour.os.date('%H')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.tonumber()converts the string to a number.hour =stores the numeric value of the server time in the variablehour.if hour < 12 thenbegins a conditional code block and checkshourto see if it is less than12. If it is, the following statement(s) are executed. If not, the following statements are skipped.return 'Good morning!'sets the value of result.elseif hour < 18 thencheckshourto see if it is less than18. If it is, the following statements are executed. If not, the following statements are skipped.- Conditions are mutually exclusive. If the first condition was true (
if), the second condition (elseif) is not evaluated. elseifis optional in a conditional code block and may be repeated.
- Conditions are mutually exclusive. If the first condition was true (
elseindicates 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.elseis optional in a conditional code block.
endends the conditional code block.
Conclusion
[edit | edit source]Congratulations! You've now created, tested, and understood a Lua script with conditions. Continue on to the Loops lesson.
See Also
[edit | edit source]References
[edit | edit source]- ↑ "Extension:Scribunto/Lua reference manual". Mediawiki. 2026. Retrieved 2026-04-04.