Lua/Modules
< 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
editThis lesson assumes you have already completed the Scribunto/Lua lesson.
Create a Lua Script with Multiple Functions
editTo 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
editTo 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
editTo 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
editCongratulations! You've now created, tested, and understood a Lua module with multiple functions. Continue on to the Variables lesson.