Lua/Modules

From Wikiversity
< Lua
Jump to navigation Jump to search

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:

  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.
  3. 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:

  1. Navigate to either the Module_talk:Sandbox page, the Wikiversity:Sandbox page, or your own user or sandbox page.
  2. 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:

  1. function p.hello() adds a function named hello.
  2. function p.meet() adds a function named meet.
  3. {{#invoke:Sandbox|hello}} calls the Sandbox module hello function.
  4. {{#invoke:Sandbox|meet}} calls the Sandbox module meet 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.

References[edit | edit source]