Lua/Variables

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 This lesson will show you how to add variables to your functions.

Prerequisites
This lesson assumes you have already completed the Modules lesson.

Create a Lua Script with a Variable
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.
 * 1) Add the following code and save the page:

Test Your Lua Script
To test your Lua script:
 * 1) Navigate to either the Module_talk:Sandbox page, the Sandbox page, or your own user or sandbox page.
 * 2) Add the following code and save the page:

The result should be: 2

Understand Your Lua Script
To understand your Lua script: Each Lua function can have one or more variables used to contain values for the function.
 * 1)   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   keyword in most cases.  Using local in this function ensures that the variable's value can only be accessed and modified inside the function.
 * 1)   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.
 * 1)   assigns the value   to.
 * Variables that are not given an initial value are equal to, indicating that they have no value.
 * 1)   takes the value of   and adds   to it, then stores the result of the calculation back in.
 * Variables can be used as both the source and destination for expressions (calculations).
 * 1)   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.
 * 1)   calls the Sandbox module   function.

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