Lua/Modules
Appearance
< 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] This lesson will show you how to add multiple functions to a module.
Prerequisites
[edit | edit source]This lesson assumes you have already completed the Scribunto/Lua lesson.
Create a Lua Script with Multiple Functions
[edit | edit source]To create a Lua script with multiple functions:
- Navigate to Module:Sandbox.
- 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.
- Add the following code and save the page:
local p = {} function p.hello() return 'Hello!' end function p.meet() return 'Nice to meet you!' end return p
Test Your Lua Script
[edit | edit source]To test your Lua script:
- Navigate to either the Module_talk:Sandbox page, the Wikiversity:Sandbox page, or your own user or sandbox page.
- Add the following code and save the page:
* {{#invoke:Sandbox|hello}} * {{#invoke:Sandbox|meet}}
The result should be:
- Hello!
- Nice to meet you!
Understand Your Lua Script
[edit | edit source]To understand your Lua script:
function p.hello()
adds a function namedhello
.function p.meet()
adds a function namedmeet
.{{#invoke:Sandbox|hello}}
calls the Sandbox modulehello
function.{{#invoke:Sandbox|meet}}
calls the Sandbox modulemeet
function.
Each Lua module can contain one or more functions that may be called individually.
Conclusion
[edit | edit source]Congratulations! You've now created, tested, and understood a Lua module with multiple functions. Continue on to the Variables lesson.