Lua/Modules
< LuaLua 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
This lesson assumes you have already completed the Scribunto/Lua lesson.
Create a Lua Script with Multiple Functions
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
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
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
Congratulations! You've now created, tested, and understood a Lua module with multiple functions. Continue on to the Variables lesson.
References
This article is issued from Wikiversity - version of the Tuesday, March 08, 2016. The text is available under the Creative Commons Attribution/Share Alike but additional terms may apply for the media files.