Lua/Variables

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. Variables are places that store values[1] This lesson will show you how to add variables to your functions.

Prerequisites[edit | edit source]

This lesson assumes you have already completed the Modules lesson.

Create a Lua Script with a Variable[edit | edit source]

To create a Lua script with a variable:

  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.variables()
    local variable = 1
 
    variable = variable + 1
    return variable
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|variables}}

The result should be:

2

Understand Your Lua Script[edit | edit source]

To understand your Lua script:

  1. local defines the scope of the variable being declared.
    If you are familiar with variable scope, be aware that Lua variables are global by default. Best practice for programmers is to use local variables whenever possible, so variables should be declared with the local keyword in most cases. Using local in this function ensures that the variable's value can only be accessed and modified inside the function.
  2. variable defines the name of the variable.
    Variable names are flexible, but cannot be a Lua keyword. For example, you could not have a variable named local.
  3. = 1 assigns the value 1 to variable.
    Variables that are not given an initial value are equal to nil, indicating that they have no value.
  4. variable = variable + 1 takes the value of variable and adds 1 to it, then stores the result of the calculation back in variable.
    Variables can be used as both the source and destination for expressions (calculations).
  5. return variable returns the current value of variable as the result of the function.
    Numeric values are implicitly converted to strings when they are returned from the module.
  6. {{#invoke:Sandbox|variables}} calls the Sandbox module variables function.

Each Lua function can have one or more variables used to contain values for the function.

Conclusion[edit | edit source]

Congratulations! You've now created, tested, and understood a Lua script with a variable. Continue on to the Expressions lesson.

See Also[edit | edit source]

References[edit | edit source]