Lua/Print version
Contents
Background
History[edit]
Lua was created in 1993 by Roberto Ierusalimschy, Luiz Henrique de Figueiredo, and Waldemar Celes, members of the Computer Graphics Technology Group at PUC-Rio, the Pontifical University of Rio de Janeiro, in Brazil. Versions of Lua prior to version 5.0 were released under a license similar to the BSD license. From version 5.0 onwards, Lua has been licensed under the MIT License.
Some of its closest relatives include Icon for its design and Python for its ease of use by non-programmers. In an article published in Dr. Dobb's Journal, Lua's creators also state that Lisp and Scheme with their single, ubiquitous data structure mechanism (the list) were a major influence on their decision to develop the table as the primary data structure of Lua.
Lua has been used in many commercial applications, such as Far Cry, Garry's Mod, Supreme Commander, World of Warcraft, Sonic the Hedgehog and Adobe Photoshop Lightroom, as well as non-commercial applications, such as Multi Theft Auto and Angband and its variants.
Lua can be embedded in Mediawiki, the software behind Wikipedia and Wikiversity, and has been enabled on Wikiversity. Thus the course material can be used directly within the Wikiversity environment.
Characteristics[edit]
Lua is designed to be extensible, i.e users are able to add new keywords, concepts, and structures to the source language.
Lua is:
- reflective
- imperative
- procedural
Introduction
Lua can be used both as a scripting/programming language on its own, and as an integrated scripting language for other platforms. This lesson focuses on using Lua with the interpreter available from Lua.org. See the next lesson to learn how to use Lua for scripting MediaWiki Scribunto/Lua extension templates now available on Wikiversity.
Prerequisites[edit]
The Lua interpreter, which can be downloaded from the official Lua website. The package includes the Lua compiler and a few sample scripts.
Lua command line interpreter[edit]
The command line Lua interpreter is a nifty tool if you need to quickly test some code. It executes lines of code as soon as you hit the Return key, and blocks of code (such as conditional statements and loops) after you complete them (with the end keyword).
If you have Lua installed, you can start the terminal and run lua to start the interpreter. If not, you can download and install it, use the repl.it Lua emulator in the browser or the Lua demo.
Here is an example session:
Lua 5.1.1 Copyright (C) 1994-2006 Lua.org, PUC-Rio
> print("Hello, world!")
Hello, world!
> print(5+7)
12
> if true then
>> print(true)
>> end
true
The first line uses the function print to output the string "Hello, world!". Numbers and booleans may also be output using print. The interpreter acknowledges code blocks with an extra '>' at the prompt.
When done, hit Ctrl-D (EOF) to close the interpreter.
Executing and compiling programs[edit]
While entering commands at the command line prompt is suitable for testing, it is not for executing scripts. Scripts are usually saved in files with the .lua file extension. To execute a script, the filename is passed as an argument to the interpreter. For example:
lua myscript.lua
You can compile your scripts using luac, the Lua compiler.
luac inputfile
This will output the bytecode to a file named luac.out. Use the -o argument to change this:
luac -o outputfile inputfile
Variables[edit]
The rest of the lesson will simply list the code—it is up to you to try it in the interpreter or save it in a file and execute it.
Lua is a dynamically-typed language. Variables don't have types, only values have types. This means that a variable can be set to a value of a type, and then to a value of another type. Consider this:
a = 15
print(a)
a = "Hello"
print(a)
Output:
15 Hello
This has advantages and disadvantages. It allows for different types of values to be used easily, but also means that unexpected types may be used, causing errors.
Value types[edit]
The following basic types are available in Lua:
- boolean: Can be true or false
- number: A real number (floating-point precision)
- string: A string of characters, such as "Hello, world!".
- function: Functions are first-class values in Lua (more on this later).
- userdata: C objects passed to Lua (more on this later).
- thread: Lua coroutines (more on this later).
- table: Tables are flexible data structures (more on this later).
- nil: Type of the value nil. nil represents the absence of a value
Scribunto Lua
Lua is implemented in MediaWiki wikis using the Scribunto/Lua extension and stored in resource pages using the Module: namespace.[1]
Create Your First Lua Script[edit]
To create your first Lua script:
- 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 return p
Test Your First Lua Script[edit]
To test your first 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}}
The result should be:
Hello!
Edit Your First Lua Script[edit]
To edit your first Lua script:
- Return to the Module:Sandbox.
- Edit the line with
return 'Hello!'and add your name inside the single quotes. You should end up with something likereturn 'Hello Lua!'. - Save the page.
- Return to the sandbox test page you used above to test your changes. Using the module's talk page is very convenient for quick testing.
- Refresh the page to see your name returned from the script.
The result should be similar to:
Hello Lua!
Understand Your First Lua Script[edit]
Now that you see what the script does, it's time to understand how it works.
local p = {}creates a local table or array for your code and names itp.function p.hello()adds a function namedhelloto the table. Functions can be invoked (called) by name from outside the module.return 'Hello!'returns the stringHello!when the function is invoked (called).endends the function.return preturns the code table to whatever process loads this Lua module.
The code that runs the script includes:
#invoke:invokes (calls) a Lua module.Sandboxspecifies the name of the module to be loaded.hellospecifies the name of the function inside the module that is to be invoked (called).
| {{#invoke:Sandbox|hello}} | Keyword | 1st Parameter | 2nd Parameter |
|---|---|---|---|
|
Code |
#invoke: |
Sandbox |
hello |
|
What it does |
specifies action - here load module and implement function |
specifies the name of the module to be loaded |
specifies the name of the function inside the module that is to be invoked (called). |
Conclusion[edit]
Congratulations! You've now created, tested, edited, and understood your first Lua script. Continue on to the Modules lesson.
References[edit]
Modules
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]
This lesson assumes you have already completed the Scribunto/Lua lesson.
Create a Lua Script with Multiple Functions[edit]
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[edit]
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[edit]
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 modulehellofunction.{{#invoke:Sandbox|meet}}calls the Sandbox modulemeetfunction.
Each Lua module can contain one or more functions that may be called individually.
Conclusion[edit]
Congratulations! You've now created, tested, and understood a Lua module with multiple functions. Continue on to the Variables lesson.
References[edit]
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[1] This lesson will show you how to add variables to your functions.
Prerequisites[edit]
This lesson assumes you have already completed the Modules lesson.
Create a Lua Script with a Variable[edit]
To create a Lua script with a variable:
- 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.variables() local variable = 1 variable = variable + 1 return variable end return p
Test Your Lua Script[edit]
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|variables}}
The result should be:
2
Understand Your Lua Script[edit]
To understand your Lua script:
localdefines 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
localkeyword in most cases. Using local in this function ensures that the variable's value can only be accessed and modified inside the function.
- 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
variabledefines 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.
- Variable names are flexible, but cannot be a Lua keyword. For example, you could not have a variable named
= 1assigns the value1tovariable.- Variables that are not given an initial value are equal to
nil, indicating that they have no value.
- Variables that are not given an initial value are equal to
variable = variable + 1takes the value ofvariableand adds1to it, then stores the result of the calculation back invariable.- Variables can be used as both the source and destination for expressions (calculations).
return variablereturns 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.
{{#invoke:Sandbox|variables}}calls the Sandbox modulevariablesfunction.
Each Lua function can have one or more variables used to contain values for the function.
Conclusion[edit]
Congratulations! You've now created, tested, and understood a Lua script with a variable. Continue on to the Expressions lesson.
See Also[edit]
References[edit]
Expressions
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] Expressions are comprised of literal values, variables, and arithmetic, relational and logical operators. This lesson will show you how to use expressions in your scripts.
Prerequisites[edit]
This lesson assumes you have already completed the Variables lesson.
Create a Lua Script with Expressions[edit]
To create a Lua script with expressions:
- 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.arithmetic() local a = 3 local b = 2 local result result = ';Arithmetic\n' result = result .. ':a is ' .. a .. '\n' result = result .. ':b is ' .. b .. '\n' result = result .. ':a + b is ' .. a + b .. '\n' result = result .. ':a - b is ' .. a - b .. '\n' result = result .. ':a * b is ' .. a * b .. '\n' result = result .. ':a / b is ' .. a / b .. '\n' result = result .. ':a % b is ' .. a % b .. '\n' result = result .. ':a ^ b is ' .. a ^ b .. '\n' result = result .. ':-a is ' .. -a .. '\n' return result end function p.relational() local a = 3 local b = 2 local result result = ';Relational\n' result = result .. ':a is ' .. a .. '\n' result = result .. ':b is ' .. b .. '\n' result = result .. ':a == b is ' .. tostring(a == b) .. '\n' result = result .. ':a ~= b is ' .. tostring(a ~= b) .. '\n' result = result .. ':a < b is ' .. tostring(a < b) .. '\n' result = result .. ':a > b is ' .. tostring(a > b) .. '\n' result = result .. ':a <= b is ' .. tostring(a <= b) .. '\n' result = result .. ':a >= b is ' .. tostring(a >= b) .. '\n' return result end function p.logical() local a = 3 local b = 2 local result result = ';Logical\n' result = result .. ':a is ' .. a .. '\n' result = result .. ':b is ' .. b .. '\n' result = result .. ':a < b and b < a is ' .. tostring(a < b and b < a) .. '\n' result = result .. ':a < b or b < a is ' .. tostring(a < b or b < a) .. '\n' result = result .. ':a < b is ' .. tostring(a < b) .. '\n' result = result .. ':not (a < b) is ' .. tostring(not (a < b)) .. '\n' return result end function p.length() local string = 'This is a string' local result result = ';Length\n' result = result .. ':The length of "' .. string .. '" is ' .. #string return result end return p
Test Your Lua Script[edit]
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|arithmetic}}
{{#invoke:Sandbox|relational}}
{{#invoke:Sandbox|logical}}
{{#invoke:Sandbox|length}}
The result should be:
- Arithmetic
- a is 3
- b is 2
- a + b is 5
- a - b is 1
- a * b is 6
- a / b is 1.5
- a % b is 1
- a ^ b is 9
- -a is -3
- Relational
- a is 3
- b is 2
- a == b is false
- a ~= b is true
- a < b is false
- a > b is true
- a <= b is false
- a >= b is true
- Logical
- a is 3
- b is 2
- a < b and b < a is false
- a < b or b < a is true
- a < b is false
- not (a < b) is true
- Length
- The length of "This is a string" is 16
Understand Your Lua Script[edit]
To understand your Lua script:
localand the following code defines the variables a, b, and result. a and b are initialized. result isnil.3and2are numeric literals.';Arithmetic\n'is a string literal. String literals may also be defined using double quotes, such as";Arithmetic\n".\nis a newline character. Content that follows will appear on a new line in the resulting text...is the concatenation operator. It appends two strings together. Numeric values are automatically converted to strings when concatenated.+,-,*, and/are add, subtract, multiply, and divide, respectively.%is the modulo or remainder operator.^is the exponentiation or 'raise to the power of' operator.-preceding a variable is the negation operator.==compares for equality.~=compares for inequality.<,>,<=, and>=compare less than, greater than, less than or equal, and greater than or equal, respectively.tostring()explicitly converts the content to a string. Logical comparisons do not automatically convert to strings.andreturns false if the left operand is false, or the value of the right operand if the left operand is true.- This left/right approach is more efficient, because
andstops evaluating as soon as it knows the result is false.
- This left/right approach is more efficient, because
orreturns true if the left operand is true, or the value of the right operand if the left operand is false.- This left/right approach is more efficient, because
orstops evaluating as soon as it knows the result is true.
- This left/right approach is more efficient, because
notreturns the true/false opposite of what follows.#returns the length of the variable that follows.
Conclusion[edit]
Congratulations! You've now created, tested, and understood a Lua script with expressions. Continue on to the Conditions lesson.
See Also[edit]
References[edit]
Conditions
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] Conditions are code structures used to make choices and control the flow of scripts. This lesson will show you how to use conditions in your scripts.
Prerequisites[edit]
This lesson assumes you have already completed the Expressions lesson.
Create a Lua Script with Conditions[edit]
To create a Lua script with conditions:
- 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.conditions() local hour local result hour = tonumber(os.date('%H')) if hour < 12 then result = 'Good morning!' elseif hour < 18 then result = 'Good afternoon!' else result = 'Good evening!' end return result end return p
Test Your Lua Script[edit]
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|conditions}}
The result should be either:
Good morning!
or
Good afternoon!
or
Good evening!
depending on the UTC time of day.
Understand Your Lua Script[edit]
To understand your Lua script:
localand the following code defines the variableshourandresult. Both arenil.os.date('%H')returns the current server time formatted in hours (%H) from 0 to 23 as a string. Server time is typically set to UTC rather than local time.tonumber()converts the string to a number.hour =stores the numeric value of the server time in the variablehour.if hour < 12 thenbegins a conditional code block and checkshourto see if it is less than12. If it is, the following statement(s) are executed. If not, the following statements are skipped.result = 'Good morning!'sets the value of result.elseif hour < 18 thencheckshourto see if it is less than18. If it is, the following statements are executed. If not, the following statements are skipped.- Conditions are mutually exclusive. If the first condition was true (if), the second condition (elseif) is not evaluated.
elseifis optional in a conditional code block and may be repeated.
elseindicates that if none of the previous conditions were true, the following statements are executed. If one of the previous statements was true, the following statements are skipped.elseis optional in a conditional code block.
endends the conditional code block.return resultreturns the current value of result as the result of the function.
Conclusion[edit]
Congratulations! You've now created, tested, and understood a Lua script with conditions. Continue on to the Loops lesson.
See Also[edit]
References[edit]
Loops
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] Loops are code structures used to repeat statements in scripts. This lesson will show you how to use loops in your scripts.
Prerequisites[edit]
This lesson assumes you have already completed the Conditions lesson.
Create a Lua Script with Loops[edit]
To create a Lua script with loops:
- 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.forloop() local i local result result = ';for\n' for i = 2, 10, 2 do result = result .. ":i = " .. i .. '\n' end return result end function p.whileloop() local i local result result = ';while\n' i = 2 while i <= 10 do result = result .. ":i = " .. i .. '\n' i = i + 2 end return result end function p.repeatloop() local i local result result = ';repeat\n' i = 2 repeat result = result .. ":i = " .. i .. '\n' i = i + 2 until i > 10 return result end return p
Test Your Lua Script[edit]
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|forloop}}
{{#invoke:Sandbox|whileloop}}
{{#invoke:Sandbox|repeatloop}}
The result should be:
- for
- i = 2
- i = 4
- i = 6
- i = 8
- i = 10
- while
- i = 2
- i = 4
- i = 6
- i = 8
- i = 10
- repeat
- i = 2
- i = 4
- i = 6
- i = 8
- i = 10
Understand Your Lua Script[edit]
To understand your Lua script for loop:
localand the following code defines the variablesiandresult. Both arenil.result = ';for\n'assigns a string literal value to the variableresult.- This could also have been written with the initial variable declaration as
local result = ';for\n'. There is no difference in functionality, only in the author's preference for coding style. Some programming languages require variables to be declared before they are used, resulting in some developers preferring to see variables declared before they are used.
- This could also have been written with the initial variable declaration as
for i = 2, 10, 2 docreates a loop code block that will vary the value of the variableifrom2to10by2.- For loops are used when the number of loops desired can be easily determined before the loop is entered. They are typically counting loops of some type.
- For loops can be sequenced either in a positive or a negative direction.
for i = 10, 2, -2 dowould count down from10to2by2. - If the increment value is not provided, the default increment is 1.
for i = 1, 10 dowould count from1to10by1.
result = result .. ":i = " .. i .. '\n'concatenates a string literal and the current value of the variableitoresult.endends the loop.- The value of the loop variable,
iin this case, will be one increment greater than the stop value when the loop ends. In this example,iwill be equal to12after the loop ends.
- The value of the loop variable,
return resultreturns the current value ofresultas the result of the function.
To understand your Lua script while loop:
localand the following code defines the variablesiandresult. Both arenil.result = ';while\n'assigns a string literal value to the variableresult.i = 2assigns the value2to the variablei.- This could also have been written with the initial variable declaration as
local i = 2.
- This could also have been written with the initial variable declaration as
while i <= 10 docreates a loop code block that will loop while the value ofiis less than10.- While loops are used when the number of loops desired is determined within the loop, such as repeating until the end of a string is reached. A while loop is used here to demonstrate the comparison in code structure between for, while, and repeat loops.
- If the while loop condition is not met, the loop code block will be skipped.
- If the while loop condition is met, the while loop condition must be altered inside the loop, or the loop will repeat forever.
result = result .. ":i = " .. i .. '\n'concatenates a string literal and the current value of the variableitoresult.i = i + 2takes the current value ofi, adds2, and stores the result ini.endends the loop.return resultreturns the current value ofresultas the result of the function.
To understand your Lua script repeat loop:
localand the following code defines the variablesiandresult. Both arenil.result = ';repeat\n'assigns a string literal value to the variableresult.i = 2assigns the value2to the variablei.repeatcreates a loop code block that will loop until the ending condition is true.- Repeat loops are used when the number of loops desired is determined within the loop, such as repeating until the end of a string is reached.
- The difference between a while loop and a repeat loop is that the while loop may not execute if the condition is not met. A repeat loop always executes at least once.
- If the repeat loop condition is met, the repeat loop condition must be altered inside the loop, or the loop will repeat forever.
result = result .. ":i = " .. i .. '\n'concatenates a string literal and the current value of the variableitoresult.i = i + 2takes the current value ofi, adds2, and stores the result ini.until i > 10sets the condition that is tested to end the loop. If the condition is false, the loop repeats. If the condition is true, the loop terminates.return resultreturns the current value ofresultas the result of the function.
Conclusion[edit]
Congratulations! You've now created, tested, and understood a Lua script with loops. Continue on to the Functions lesson.
See Also[edit]
References[edit]
Functions
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] Functions are code structures used to encapsulate a series of statements that may be called as needed. This lesson will show you how to use functions in your scripts.
Prerequisites[edit]
This lesson assumes you have already completed the Loops lesson.
Create a Lua Script with Functions[edit]
To create a Lua script with 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 = {} local function toCelsius(f) return (f - 32) * 5 / 9 end local function toFahrenheit(c) return c * 9 / 5 + 32 end function p.functions() local temperature local result result = ';Fahrenheit to Celsius\n' for temperature = 0, 100, 10 do result = result .. ':' .. temperature .. ' °F is ' .. string.format('%.1f', toCelsius(temperature)) .. ' °C\n' end result = result .. ';Celsius to Fahrenheit\n' for temperature = 0, 100, 10 do result = result .. ':' .. temperature .. ' °C is ' .. string.format('%.1f', toFahrenheit(temperature)) .. ' °F\n' end return result end return p
Test Your Lua Script[edit]
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|functions}}
The result should be:
- Fahrenheit to Celsius
- 0 °F is -17.8 °C
- 10 °F is -12.2 °C
- 20 °F is -6.7 °C
- 30 °F is -1.1 °C
- 40 °F is 4.4 °C
- 50 °F is 10.0 °C
- 60 °F is 15.6 °C
- 70 °F is 21.1 °C
- 80 °F is 26.7 °C
- 90 °F is 32.2 °C
- 100 °F is 37.8 °C
- Celsius to Fahrenheit
- 0 °C is 32.0 °F
- 10 °C is 50.0 °F
- 20 °C is 68.0 °F
- 30 °C is 86.0 °F
- 40 °C is 104.0 °F
- 50 °C is 122.0 °F
- 60 °C is 140.0 °F
- 70 °C is 158.0 °F
- 80 °C is 176.0 °F
- 90 °C is 194.0 °F
- 100 °C is 212.0 °F
Understand Your Lua Script[edit]
To understand your Lua script toCelsius function:
local function toCelsius(f)declares a local function namedtoCelsiusthat accepts a single parameterf, which is the Fahrenheit temperature to be converted.- Declaring the function as
localprevents it from being called from outside the module.
- Declaring the function as
return (f - 32) * 5 / 9converts the Fahrenheit temperature into Celsius and returns the result.endends the function.
To understand your Lua script toFahrenheit function:
local function toFahrenheit(c)declares a local function namedtoFahrenheitthat accepts a single parameterc, which is the Celsius temperature to be converted.- Declaring the function as
localprevents it from being called from outside the module.
- Declaring the function as
return c * 9 / 5 + 32converts the Celsius temperature into Fahrenheit and returns the result.endends the function.
To understand your Lua script functions function:
function p.functions()declares a function namedfunctions.- This function is not declared
local, so it can be called from outside the module.
- This function is not declared
localand the following code defines the variablestemperatureandresult. Both arenil.result = ';Fahrenheit to Celsius\n'assigns a string literal value to the variableresult.for temperature = 0, 100, 10 docreates a loop code block that will vary the value of the variabletemperaturefrom0to100by10.toCelsius(temperature)calls thetoCelsiusfunction and passes in the current value oftemperatureas the temperature to be converted.string.format()calls thestringlibraryformatfunction to format the returned Celsius temperature.'%.1f'indicates that the resulting format (%) should be a single decimal place (.1) floating point (f) value.toFahrenheit(temperature)calls thetoFahrenheitfunction and passes in the current value oftemperatureas the temperature to be converted.string.format()calls thestringlibraryformatfunction to format the returned Fahrenheit temperature.'%.1f'indicates that the resulting format (%) should be a single decimal place (.1) floating point (f) value.return resultreturns the current value ofresultas the result of the function.
It should be noted that this script makes use of three different function types:
- locally accessible functions (
toCelsius,toFahrenheit) - globally accessible functions (
functions) - library functions (
string.format).
Conclusion[edit]
Congratulations! You've now created, tested, and understood a Lua script with functions. Continue on to the Tables lesson.
See Also[edit]
References[edit]
Tables
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] Tables are associative arrays or collections of data with key / value pairs that may be used to hold, organize and access data. This lesson will show you how to use tables in your scripts.
Prerequisites[edit]
This lesson assumes you have already completed the Functions lesson.
Create a Lua Script with Tables[edit]
To create a Lua script with tables:
- 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 = {} local function tableToString(t) local key local value local result result = '' for key, value in pairs(t) do if (tonumber(key) ~= nil) then result = result .. ':table[' .. key .. '] is ' .. value .. '\n' else result = result .. ':table[\'' .. key .. '\'] is ' .. value .. '\n' end end return result end function p.sequence() local numbers = {10, 20, 30} local result result = ';sequence\n' result = result .. tableToString(numbers) return result end function p.dictionary() local languages = { ['de'] = 'German', ['en'] = 'English', ['es'] = 'Spanish', ['fr'] = 'French', ['it'] = 'Italian', ['ja'] = 'Japanese', ['ko'] = 'Korean', ['ru'] = 'Russian', ['zh'] = 'Chinese' } local result result = ';dictionary\n' result = result .. tableToString(languages) return result end return p
Test Your Lua Script[edit]
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|sequence}}
{{#invoke:Sandbox|dictionary}}
The result should be similar to:
- sequence
- table[1] is 10
- table[2] is 20
- table[3] is 30
- dictionary
- table['es'] is Spanish
- table['ja'] is Japanese
- table['fr'] is French
- table['ru'] is Russian
- table['de'] is German
- table['ko'] is Korean
- table['en'] is English
- table['zh'] is Chinese
- table['it'] is Italian
Understand Your Lua Script[edit]
To understand your Lua script tableToString function:
local function tableToString(t)declares a local function namedtableToStringthat accepts a single parametert, which is the table to be converted to a string.localand the following code defines the variableskey,value, andresult. All arenil.result = ''assigns an empty string literal value to the variableresult.for key, value in pairs(t) docreates a loop code block that will vary the value of the variableskeyandvaluefor each key/value data pair in the tablet.if (tonumber(key) ~= nil) thentests to see if the key can be converted to a number. If it can, the key is displayed as a number (without quotes). If it can't be converted, the key is displayed as a literal string (with quotes).result = result .. ':table[' .. key .. '] is ' .. value .. '\n'orresult = result .. ':table[\'' .. key .. '\'] is ' .. value .. '\n'adds the current key and value to the result.- The
table[key]notation is a common way to reference individual table keys to access their associated values. - To display quotes inside a string, you must either switch between quote identifiers ("/'), or use the \ character to 'escape' the quote, which forces it to be part of the string rather than terminate the string.
- The
endends the loop.return resultreturns the current value ofresultas the result of the function.endends the function.
To understand your Lua script sequence function:
function p.sequence()declares a function named sequence.local numbers = {10, 20, 30}defines a local table variable namednumbers, which is initialized with three values.- When table values are specified without matching keys, Lua automatically adds numeric keys for the values as a sequence from 1 to N, the number of values added. This allows Lua tables to be used similar to how arrays are used in other programming languages. For example, the second value in the table could be referenced as
numbers[2], and the table values could be processed with a for loop.
- When table values are specified without matching keys, Lua automatically adds numeric keys for the values as a sequence from 1 to N, the number of values added. This allows Lua tables to be used similar to how arrays are used in other programming languages. For example, the second value in the table could be referenced as
local resultdefines the variableresultand initializes it tonil.result = ';sequence\n'assigns a literal string value to the variableresult.result = result .. tableToString(numbers)calls thetableToStringfunction, passing the tablenumbersas the parameter and concatenates the returned value to the variableresult.return resultreturns the current value ofresultas the result of the function.endends the function.
To understand your Lua script dictionary function:
function p.dictionary()declares a function named dictionary.local languages = {and the following code defines a local table variable namedlanguages, which is initialized with 9 key/value pairs.- When table values are specified with matching keys, Lua uses the specified keys instead of numeric key values.
- Lua tables with specified key values cannot be used as arrays using
table[number]notation. - Lua tables with specified key values can be used as associative arrays using
table[key]notation, such aslanguages['en']. Quotes around string literal keys are required with this notation format. - Lua tables with specified key values can also be used as associative arrays using
table.keynotation, such aslanguages.en. Quotes around string literal keys are not required with this notation format.
local resultdefines the variableresultand initializes it tonil.result = ';dictionary\n'assigns a literal string value to the variableresult.result = result .. tableToString(languages)calls thetableToStringfunction, passing the tablelanguagesas the parameter and concatenates the returned value to the variableresult.return resultreturns the current value ofresultas the result of the function.endends the function.
It is important to note that the for loop to process table pairs will process all values in the table, but tables with specified key values may not be processed in the order they were created.
Conclusion[edit]
Congratulations! You've now created, tested, and understood a Lua script with tables. Continue on to the Errors lesson.
See Also[edit]
References[edit]
Errors
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 troubleshoot script errors and handle run-time errors in your scripts.
Prerequisites[edit]
This lesson assumes you have already completed the Tables lesson.
Create a Lua Script with Errors and Error Handling[edit]
To create a Lua script with errors and error handling:
- 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 = {} local function reciprocal1(value) return 1 / value end function p.test1(frame) local value = frame.args[1] return reciprocal1(value) end local function reciprocal2(value) if value == nil then error('value must exist') end if tonumber(value) == nil then error('value must be a number') end if tonumber(value) == 0 then error('value must not be 0') end return 1 / value end function p.test2(frame) local value = frame.args[1] return reciprocal2(value) end local function reciprocal3(value) assert(value, 'value must exist') assert(tonumber(value), 'value must be a number') assert(tonumber(value) ~= 0, 'value must not be zero') return 1 / value end function p.test3(frame) local value = frame.args[1] return reciprocal3(value) end function p.test4(frame) local value = frame.args[1] if pcall(function () result = reciprocal3(value) end) then return result else return 'Error: Value must exist, must be numeric, and not zero.' end end return p
Test Your Lua Script[edit]
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:
;Reciprocal 1
:{{#invoke:Sandbox|test1}}
:{{#invoke:Sandbox|test1|x}}
:{{#invoke:Sandbox|test1|0}}
:{{#invoke:Sandbox|test1|2}}
;Reciprocal 2
:{{#invoke:Sandbox|test2}}
:{{#invoke:Sandbox|test2|x}}
:{{#invoke:Sandbox|test2|0}}
:{{#invoke:Sandbox|test2|2}}
;Reciprocal 3
:{{#invoke:Sandbox|test3}}
:{{#invoke:Sandbox|test3|x}}
:{{#invoke:Sandbox|test3|0}}
:{{#invoke:Sandbox|test3|2}}
;Reciprocal 4
:{{#invoke:Sandbox|test4}}
:{{#invoke:Sandbox|test4|x}}
:{{#invoke:Sandbox|test4|0}}
:{{#invoke:Sandbox|test4|2}}
The result should be similar to:
- Reciprocal 1
- Script error
- Script error
- inf
- 0.5
- Reciprocal 2
- Script error
- Script error
- Script error
- 0.5
- Reciprocal 3
- Script error
- Script error
- Script error
- 0.5
- Reciprocal 4
- Error: Value must exist, must be numeric, and not zero.
- Error: Value must exist, must be numeric, and not zero.
- Error: Value must exist, must be numeric, and not zero.
- 0.5
Understand Your Lua Script[edit]
To understand your Lua script reciprocal1 function:
local function reciprocal1(value)declares a local function namedreciprocal1that accepts a single parametervalue, which is the value whose reciprocal will be returned.return 1 / valuereturns the reciprocal of value.endends the function.
To understand your Lua script test1 function:
function p.test1(frame)declares a local function namedtest1that accepts a single parameterframe, which is the object used to access parameters passed from #invoke.local value = frame.args[1]defines a local variable namedvalueand assigns the value of the first frame argument (parameter) passed with #invoke.return reciprocal1(value)calls thereciprocal1function, passing the variablevalueand returns the result.endends the function.
To understand your Lua script reciprocal2 function:
local function reciprocal2(value)declares a local function namedreciprocal2that accepts a single parametervalue, which is the value whose reciprocal will be returned.if value == nil thencreates a conditional code block and tests to see ifvalueisnil. If it is, an error is generated.error('value must exist')generates an error with the given literal string as the error statement. Usingerror()allows the script writer to determine the text of the error message that is returned to the calling function or wiki page that invoked the function.- When an error is generated, execution immediately returns to the calling function. Any additional code in the same function that comes after the error is not processed.
if tonumber(value) == nilcreates a conditional code block and tests to see ifvalueis numeric. If it is not,tonumberreturnsniland an error is generated.if tonumber(value) == 0creates a conditional code block and tests to see ifvalueis0. If it is, an error is generated.return 1 / valuereturns the reciprocal of value.endends the function.
To understand your Lua script test2 function:
function p.test2(frame)and the following code declares a local function namedtest2that accepts a single parameterframe, which is the object used to access parameters passed from #invoke.local value = frame.args[1]defines a local variable namedvalueand assigns the value of the first frame argument (parameter) passed with #invoke.return reciprocal2(value)calls thereciprocal2function, passing the variablevalueand returns the result.endends the function.
To understand your Lua script reciprocal3 function:
local function reciprocal3(value)declares a local function namedreciprocal3that accepts a single parametervalue, which is the value whose reciprocal will be returned.assert(value, 'value must exist')creates a self-contained conditional code block and tests to see ifvalueisnilIf it is, an error is generated.- It is best practice to use
assertto document and test any assumptions that are made regarding passed parameters.
- It is best practice to use
assert(tonumber(value), 'value must be a number')creates a self-contained conditional code block and tests to see ifvalueis numeric. If it is not,tonumberreturnsniland an error is generated.assert(tonumber(value) ~= 0, 'value must not be zero')creates a conditional code block and tests to see ifvalueis0. If it is, an error is generated.return 1 / valuereturns the reciprocal of value.endends the function.
To understand your Lua script test3 function:
function p.test3(frame)and the following code declares a local function namedtest3that accepts a single parameterframe, which is the object used to access parameters passed from #invoke.local value = frame.args[1]defines a local variable namedvalueand assigns the value of the first frame argument (parameter) passed with #invoke.return reciprocal3(value)calls thereciprocal3function, passing the variablevalueand returns the result.endends the function.
To understand your Lua script test4 function:
function p.test4(frame)and the following code declares a local function namedtest3that accepts a single parameterframe, which is the object used to access parameters passed from #invoke.local value = frame.args[1]defines a local variable namedvalueand assigns the value of the first frame argument (parameter) passed with #invoke.if pcall(function () result = reciprocal3(value) end) thencreates a conditional code block that calls thereciprocal3function, passingvalueand storing the result. If no error occurs,resultis returned. If an error occurs, a literal string is returned instead.pcall()uses the pcall (protected call) function to call a function and catch any errors that occur.function () ... endcreates a self-contained anonymous function that executes the code in ... as a function call.- The anonymous function is necessary to save the result of the
reciprocal3function while also usingpcall()to catch any errors that occur.
- The anonymous function is necessary to save the result of the
endends the function.
Conclusion[edit]
Congratulations! You've now created, tested, and understood a Lua script with error handling. Continue on to the Math Library lesson or return to the main Lua page to learn about other Lua code libraries.
See Also[edit]
References[edit]
Math Library
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 use the Lua Math library in your scripts.
Prerequisites[edit]
This lesson assumes you have already completed the Frame Object lesson.
Create a Lua Script that Uses the Math Library[edit]
To create a Lua script that uses the Math library:
- 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.abs(frame) local x = frame.args[1] return ';abs\n:math.abs(' .. x .. ') is ' .. math.abs(x) .. '\n' end function p.acos(frame) local x = frame.args[1] return ';acos\n:math.acos(' .. x .. ') is ' .. math.acos(x) .. '\n' end function p.asin(frame) local x = frame.args[1] return ';asin\n:math.asin(' .. x .. ') is ' .. math.asin(x) .. '\n' end function p.atan(frame) local x = frame.args[1] return ';atan\n:math.atan(' .. x .. ') is ' .. math.atan(x) .. '\n' end function p.atan2(frame) local y = frame.args[1] local x = frame.args[2] return ';atan2\n:math.atan2(' .. y .. ', ' .. x .. ') is ' .. math.atan2(y, x) .. '\n' end function p.ceil(frame) local x = frame.args[1] return ';ceil\n:math.ceil(' .. x .. ') is ' .. math.ceil(x) .. '\n' end function p.cos(frame) local x = frame.args[1] return ';cos\n:math.cos(' .. x .. ') is ' .. math.cos(x) .. '\n' end function p.cosh(frame) local x = frame.args[1] return ';cosh\n:math.cosh(' .. x .. ') is ' .. math.cosh(x) .. '\n' end function p.deg(frame) local x = frame.args[1] return ';deg\n:math.deg(' .. x .. ') is ' .. math.deg(x) .. '\n' end function p.exp(frame) local x = frame.args[1] return ';exp\n:math.exp(' .. x .. ') is ' .. math.exp(x) .. '\n' end function p.floor(frame) local x = frame.args[1] return ';floor\n:math.floor(' .. x .. ') is ' .. math.floor(x) .. '\n' end function p.fmod(frame) local x = frame.args[1] local y = frame.args[2] return ';fmod\n:math.fmod(' .. x .. ', ' .. y .. ') is ' .. math.fmod(x, y) .. '\n' end function p.frexp(frame) local x = frame.args[1] return ';frexp\n:math.frexp(' .. x .. ') is ' .. math.frexp(x) .. '\n' end function p.huge() return ';huge\n:math.huge is ' .. math.huge .. '\n' end function p.ldexp(frame) local m = frame.args[1] local e = frame.args[2] return ';ldexp\n:math.ldexp(' .. m .. ', ' .. e .. ') is ' .. math.ldexp(m, e) .. '\n' end function p.log(frame) local x = frame.args[1] return ';log\n:math.log(' .. x .. ') is ' .. math.log(x) .. '\n' end function p.log10(frame) local x = frame.args[1] return ';log10\n:math.log10(' .. x .. ') is ' .. math.log10(x) .. '\n' end function p.max(frame) local x = frame.args[1] local y = frame.args[2] return ';max\n:math.max(' .. x .. ', ' .. y .. ') is ' .. math.max(x, y) .. '\n' end function p.min(frame) local x = frame.args[1] local y = frame.args[2] return ';min\n:math.min(' .. x .. ', ' .. y .. ') is ' .. math.min(x, y) .. '\n' end function p.modf(frame) local x = frame.args[1] return ';modf\n:math.modf(' .. x .. ') is ' .. math.modf(x) .. '\n' end function p.pi() return ';pi\n:math.pi is ' .. math.pi .. '\n' end function p.pow(frame) local x = frame.args[1] local y = frame.args[2] return ';pow\n:math.pow(' .. x .. ', ' .. y .. ') is ' .. math.pow(x, y) .. '\n' end function p.rad(frame) local x = frame.args[1] return ';rad\n:math.rad(' .. x .. ') is ' .. math.rad(x) .. '\n' end function p.random(frame) local m = frame.args[1] local n = frame.args[2] return ';random\n:math.random(' .. m .. ', ' .. n .. ') is ' .. math.random(m, n) .. '\n' end function p.randomseed(frame) local m = frame.args[1] local n = frame.args[2] math.randomseed(os.time()) return ';randomseed\n:math.random(' .. m .. ', ' .. n .. ') is ' .. math.random(m, n) .. '\n' end function p.sin(frame) local x = frame.args[1] return ';sin\n:math.sin(' .. x .. ') is ' .. math.sin(x) .. '\n' end function p.sinh(frame) local x = frame.args[1] return ';sinh\n:math.sinh(' .. x .. ') is ' .. math.sinh(x) .. '\n' end function p.sqrt(frame) local x = frame.args[1] return ';sqrt\n:math.sqrt(' .. x .. ') is ' .. math.sqrt(x) .. '\n' end function p.tan(frame) local x = frame.args[1] return ';tan\n:math.tan(' .. x .. ') is ' .. math.tan(x) .. '\n' end function p.tanh(frame) local x = frame.args[1] return ';tanh\n:math.tanh(' .. x .. ') is ' .. math.tanh(x) .. '\n' end return p
Test Your Lua Script[edit]
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|abs|-1}}
{{#invoke:Sandbox|acos|1}}
{{#invoke:Sandbox|asin|1}}
{{#invoke:Sandbox|atan|1}}
{{#invoke:Sandbox|atan2|1|1}}
{{#invoke:Sandbox|ceil|1.5}}
{{#invoke:Sandbox|cos|0.78539816339745}}
{{#invoke:Sandbox|cosh|0.78539816339745}}
{{#invoke:Sandbox|deg|0.78539816339745}}
{{#invoke:Sandbox|exp|1}}
{{#invoke:Sandbox|floor|1.5}}
{{#invoke:Sandbox|fmod|5|3}}
{{#invoke:Sandbox|frexp|1}}
{{#invoke:Sandbox|huge}}
{{#invoke:Sandbox|ldexp|1|2}}
{{#invoke:Sandbox|log| 2.718281828459}}
{{#invoke:Sandbox|log10|100}}
{{#invoke:Sandbox|max|1|2}}
{{#invoke:Sandbox|min|1|2}}
{{#invoke:Sandbox|modf|1.5}}
{{#invoke:Sandbox|pi}}
{{#invoke:Sandbox|pow|10|2}}
{{#invoke:Sandbox|rad|45}}
{{#invoke:Sandbox|random|1|6}}
{{#invoke:Sandbox|randomseed|1|6}}
{{#invoke:Sandbox|sin|0.78539816339745}}
{{#invoke:Sandbox|sinh|0.78539816339745}}
{{#invoke:Sandbox|sqrt|100}}
{{#invoke:Sandbox|tan|0.78539816339745}}
{{#invoke:Sandbox|tanh|0.78539816339745}}
The result should be similar to:
- abs
- math.abs(-1) is 1
- acos
- math.acos(1) is 0
- asin
- math.asin(1) is 1.5707963267949
- atan
- math.atan(1) is 0.78539816339745
- atan2
- math.atan2(1, 1) is 0.78539816339745
- ceil
- math.ceil(1.5) is 2
- cos
- math.cos(0.78539816339745) is 0.70710678118655
- cosh
- math.cosh(0.78539816339745) is 1.324609089252
- deg
- math.deg(0.78539816339745) is 45
- exp
- math.exp(1) is 2.718281828459
- floor
- math.floor(1.5) is 1
- fmod
- math.fmod(5, 3) is 2
- frexp
- math.frexp(1) is 0.5
- huge
- math.huge is inf
- ldexp
- math.ldexp(1, 2) is 4
- log
- math.log( 2.718281828459) is 0.99999999999998
- log10
- math.log10(100) is 2
- max
- math.max(1, 2) is 2
- min
- math.min(1, 2) is 1
- modf
- math.modf(1.5) is 1
- pi
- math.pi is 3.1415926535898
- pow
- math.pow(10, 2) is 100
- rad
- math.rad(45) is 0.78539816339745
- random
- math.random(1, 6) is 2
- randomseed
- math.random(1, 6) is 1
- sin
- math.sin(0.78539816339745) is 0.70710678118655
- sinh
- math.sinh(0.78539816339745) is 0.86867096148601
- sqrt
- math.sqrt(100) is 10
- tan
- math.tan(0.78539816339745) is 1
- tanh
- math.tanh(0.78539816339745) is 0.65579420263267
Understand Your Lua Script[edit]
To understand your Lua script:
math.abs(x)returns the absolute value ofxreturns .math.acos(x)returns the arc cosine ofx(given in radians).math.asin(x)returns the arc sine ofx(given in radians).math.atan(x)returns the arc tangent ofx(given in radians).math.atan2(y, x)returns the arc tangent ofy/x(given in radians), using the signs of both parameters to find the quadrant of the result.math.ceil(x)returns the smallest integer larger than or equal tox.math.cos(x)returns the cosine ofx(given in radians).math.cosh(x)returns the hyperbolic cosine ofx.math.deg(x)returns the anglex(given in radians) in degrees.math.exp(x)returns the valuee^x.math.floor(x)returns the largest integer smaller than or equal tox.math.fmod(x, y)returns the remainder of the division ofxbyythat rounds the quotient towards zero.math.frexp(x)returns two values m and e such thatx= m times 2^e, e is an integer, and the absolute value of m is in the range [0.5, 1)math.hugereturns the value representing positive infinity; larger than or equal to any other numerical value.math.ldexp(m, e)returnsmtimes2^e(eshould be an integer).math.log(x)returns the natural logarithm ofx.math.log10(x)returns the base-10 logarithm ofx.math.max(x, y)returns the maximum value among its arguments.math.min(x, y)returns the minimum value among its arguments.math.modf(x)returns two numbers, the integral part ofxand the fractional part ofx.math.pireturns the value of pi.math.pow(x, y)returnsx^y.math.rad(x)returns the anglex(given in degrees) in radians.math.random(m, n)returns a pseudo-random integer in the range[m,n].- Note that unless randomseed is called first, the random number sequence will be the same every time, meaning not random.
math.randomseed(os.time())seeds the random number generator with the current server operating system elapsed time in seconds.math.sin(x)returns the sine ofx(given in radians).math.sinh(x)returns the hyperbolic sine ofx.math.sqrt(x)returns the square root ofx.math.tan(x)returns the tangent ofx(given in radians).math.tanh(x)returns the hyperbolic tangent ofx.
Conclusion[edit]
Congratulations! You've now created, tested, and understood a Lua script that uses the Math library. Return to the main Lua page to learn about other Lua code libraries.
See Also[edit]
References[edit]
OS Library
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 use the Lua OS library in your scripts.
Prerequisites[edit]
This lesson assumes you have already completed the Tables lesson.
Create a Lua Script that Uses the OS Library[edit]
To create a Lua script that uses the OS library:
- 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.osclock() return ';clock\n:' .. os.clock() .. '\n' end function p.osdate() return ';date\n:' .. os.date() .. '\n' end function p.osdifftime() local t1 = {year = 2014, month = 1, day = 1, hour = 0, min = 0, sec = 0, isdst = false} local t2 = {year = 2014, month = 12, day = 31, hour = 23, min = 59, sec = 59, isdst = false} return ';difftime\n:' .. os.difftime(os.time(t2), os.time(t1)) .. '\n' end function p.ostime() return ';time\n:' .. os.time() .. '\n' end return p
Test Your Lua Script[edit]
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|osclock}}
{{#invoke:Sandbox|osdate}}
{{#invoke:Sandbox|osdifftime}}
{{#invoke:Sandbox|ostime}}
The result should be similar to:
- clock
- 0.003786627
- date
- Sat 28 Dec 2013 03:20:55 AM UTC
- difftime
- 31535999
- time
- 1388200855
Understand Your Lua Script[edit]
To understand your Lua script:
os.clock()returns the approximate amount of CPU time used by the script.os.date()returns the current date.local t1 = {year = 2014, month = 1, day = 1, hour = 0, min = 0, sec = 0, isdst = false}defines a local variablet1as a table with the given date and time values.isdst = falseindicates that the time value is not daylight savings time.
local t2 = {year = 2014, month = 12, day = 31, hour = 23, min = 59, sec = 59, isdst = false}defines a local variablet2as a table with the given date and time values.os.difftime(os.time(t2), os.time(t1))returns the difference in seconds betweent1andt2.os.time()returns the current time in seconds.
Conclusion[edit]
Congratulations! You've now created, tested, and understood a Lua script that uses the OS library. Return to the main Lua page to learn about other Lua code libraries.
See Also[edit]
References[edit]
String Library
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 use the Lua String library in your scripts.
Prerequisites[edit]
This lesson assumes you have already completed the Tables lesson.
Create a Lua Script that Uses the String Library[edit]
To create a Lua script that uses the String library:
- 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.byte() return ';byte\n:string.byte(\'A\') is ' .. string.byte('A') .. '\n' end function p.char() return ';char\n:string.char(65) is ' .. string.char(65) .. '\n' end function p.find() return ';find\n:string.find(\'that\', \'at\') is ' .. string.find('that', 'at') .. '\n' end function p.format() return ';format\n:string.format(\'%.2f\', 0) is ' .. string.format('%.2f', 0) .. '\n' end function p.gmatch() local result = ';gmatch\n:' for word in string.gmatch('This is a test', '%w+') do result = result .. word .. '-' end return result .. '\n' end function p.gsub() return ';gsub\n:string.gsub(\'This is a test\', \'%s\', \'-\') is ' .. string.gsub('This is a test', '%s', '-') .. '\n' end function p.len() return ';len\n:string.len(\'len\') is ' .. string.len('len') .. '\n' end function p.lower() return ';lower\n:string.lower(\'LOWER\') is ' .. string.lower('LOWER') .. '\n' end function p.match() return ';match\n:string.match(\'This is a test!\', \'.\', -1) is ' .. string.match('This is a test!', '.', -1) .. '\n' end function p.rep() return ';rep\n:string.rep(\'*\', 5) is ' .. string.rep('*', 5) .. '\n' end function p.reverse() return ';reverse\n:string.reverse(\'reverse\') is ' .. string.reverse('reverse') .. '\n' end function p.sub() return ';sub\n:string.sub(\'that\', 2, 3) is ' .. string.sub('that', 2, 3) .. '\n' end function p.upper() return ';upper\n:string.upper(\'upper\') is ' .. string.upper('upper') .. '\n' end return p
Test Your Lua Script[edit]
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|byte}}
{{#invoke:Sandbox|char}}
{{#invoke:Sandbox|find}}
{{#invoke:Sandbox|format}}
{{#invoke:Sandbox|gmatch}}
{{#invoke:Sandbox|gsub}}
{{#invoke:Sandbox|len}}
{{#invoke:Sandbox|lower}}
{{#invoke:Sandbox|match}}
{{#invoke:Sandbox|rep}}
{{#invoke:Sandbox|reverse}}
{{#invoke:Sandbox|sub}}
{{#invoke:Sandbox|upper}}
The result should be:
- byte
- string.byte('A') is 65
- char
- string.char(65) is A
- find
- string.find('that', 'at') is 3
- format
- string.format('%.2f', 0) is 0.00
- gmatch
- This-is-a-test-
- gsub
- string.gsub('This is a test', '%s', '-') is This-is-a-test
- len
- string.len('len') is 3
- lower
- string.lower('LOWER') is lower
- match
- string.match('This is a test!', '.', -1) is !
- rep
- string.rep('*', 5) is *****
- reverse
- string.reverse('reverse') is esrever
- sub
- string.sub('that', 2, 3) is ha
- upper
- string.upper('upper') is UPPER
Understand Your Lua Script[edit]
To understand your Lua script:
string.byte('A')returns the numeric ASCII value of the character(s) in the string.string.char(65)returns the character equivalent of the ASCII value(s) given.string.find('that', 'at')returns the numeric position of the second string within the first string.string.format('%.2f', 0)returns the second and any additional parameters formatted based on the first parameter string.- See fprintf for format specifiers.
for word in string.gmatch('This is a test', '%w+') doprocesses the first parameter by repeatedly returning a string matching the pattern specified by the second parameter.- See Patterns for pattern specifiers.
string.gsub('This is a test', '%s', '-')returns the first parameter with each occurrence of the pattern indicated by the second parameter replaced by the third parameter.- See Patterns for pattern specifiers.
string.len('len')returns the length of the string.string.lower('LOWER')returns the string converted to lower case.string.match('This is a test!', '.', -1)returns the substring of the first parameter matching the second parameter beginning at the position specified by the third parameter.- See Patterns for pattern specifiers.
string.rep('*', 5)returns the string repeated the given number of times.string.reverse('reverse')returns the string reversed.string.sub('that', 2, 3)returns the substring of the first parameter starting at the second parameter and ending at the third parameter.string.upper('upper')returns the string converted to upper case.
Conclusion[edit]
Congratulations! You've now created, tested, and understood a Lua script that uses the String library. Return to the main Lua page to learn about other Lua code libraries.
See Also[edit]
References[edit]
Table Library
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 use the Lua Table library in your scripts.
Prerequisites[edit]
This lesson assumes you have already completed the Tables lesson.
Create a Lua Script that Uses the Table Library[edit]
To create a Lua script that uses the Table library:
- 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.tablelibrary() local numbers = {} local result math.randomseed(os.time()) for i = 1, 10, 1 do table.insert(numbers, math.random(1, 10)) end result = ';random numbers\n' result = result .. ':' .. table.concat(numbers, ', ') .. '\n' table.sort(numbers) result = result .. ';sorted numbers\n' result = result .. ':' .. table.concat(numbers, ', ') .. '\n' table.remove(numbers, 1) result = result .. ';after removing the first value\n' result = result .. ':' .. table.concat(numbers, ', ') .. '\n' table.sort(numbers, function(a, b) return a > b end) result = result .. ';sorted in descending order\n' result = result .. ':' .. table.concat(numbers, ', ') .. '\n' return result end return p
Test Your Lua Script[edit]
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|tablelibrary}}
The result should be similar to:
- random numbers
- 2, 7, 5, 7, 5, 4, 9, 1, 10, 4
- sorted numbers
- 1, 2, 4, 4, 5, 5, 7, 7, 9, 10
- after removing the first value
- 2, 4, 4, 5, 5, 7, 7, 9, 10
- sorted in descending order
- 10, 9, 7, 7, 5, 5, 4, 4, 2
Understand Your Lua Script[edit]
To understand your Lua script descending function:
local function descending(first, second)declares a local function nameddescendingthat accepts two parameters,firstandsecond.return (first > second)returns true if the first is greater than the second, which will result in values being sorted in descending order.
To understand your Lua script tablelibrary function:
local numbers = {}defines an empty table variable namednumbers.math.randomseed(os.time())seeds the Lua random number generator with the current server operating system elapsed time in seconds.- If the random number generator is not seeded, it will return the same sequence of numbers every time.
- The MediaWiki software caches page results. It is necessary to purge the server page cache to see new results. See
{{Purge}}for more information.
for i = 1, 10, 1 docreates a loop code block that will repeat10times.table.insert(numbers, math.random(1, 10))calls themathlibraryrandomfunction to retrieve a random number between1and10, inclusive, and then inserts that value into thenumberstable.table.concat(numbers, ', ')retrieves the values in the tablenumbersand converts them into a string concatenated with', 'separators between each value.table.sort(numbers)sorts thenumberstable in the default ascending order.table.remove(numbers, 1)removes the element in position1from the table.- Since the table was sorted prior to removal, this will remove the lowest value from the table.
table.sort(numbers, descending)sorts the table using a customdescendingcomparison function.
Conclusion[edit]
Congratulations! You've now created, tested, and understood a Lua script that uses the Table library. Return to the main Lua page to learn about other Lua code libraries.
See Also[edit]
References[edit]
Frame Object
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 use the Lua Frame object in your scripts.
Prerequisites[edit]
This lesson assumes you have already completed the Tables lesson.
Create a Lua Script that Uses the Frame Object[edit]
To create a Lua script that uses the Frame object:
- 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 = {} local function tableToString(t) local key local value local result result = '' for key, value in pairs(t) do if (tonumber(key) ~= nil) then result = result .. ':table[' .. key .. '] is ' .. value .. '\n' else result = result .. ':table[\'' .. key .. '\'] is ' .. value .. '\n' end end return result end function p.args(frame) return ';args\n' .. tableToString(frame.args) end function p.callParserFunction(frame) return ';callParserFunction\n:' .. frame:callParserFunction('#time', 'Y-m-d H:i:s') .. '\n' end function p.expandTemplate(frame) return ';expandTemplate\n:' .. frame:expandTemplate({title = 'Template:Sandbox', args = {'arg1', 'arg2'}}) .. '\n' end function p.extensionTag(frame) return ';extensionTag\n:' .. frame:extensionTag('nowiki', '[[text]]', {}) .. '\n' end function p.getParent(frame) frame = frame:getParent() return ';getParent\n:' .. frame:getTitle() .. '\n' end function p.getTitle(frame) return ';getTitle\n:' .. frame:getTitle() .. '\n' end return p
Test Your Lua Script[edit]
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|args|These|are|arg3=frame args.}}
{{#invoke:Sandbox|callParserFunction}}
{{#invoke:Sandbox|expandTemplate}}
{{#invoke:Sandbox|extensionTag}}
{{#invoke:Sandbox|getParent}}
{{#invoke:Sandbox|getTitle}}
The result should be similar to:
- args
- table[1] is These
- table[2] is are
- table['arg3'] is frame args.
- callParserFunction
- 2013-12-20 02:20:13
- expandTemplate
- 2
- extensionTag
- [[text]]
- getParent
- Module talk:Sandbox
- getTitle
- Module:Sandbox
Understand Your Lua Script[edit]
To understand your Lua script:
local function tableToString(t)declares a local function namedtableToStringthat accepts a single parametert, which is the table to be converted to a string.- See Lua/Tables for more information.
function p.args(frame)declares a function namedargswhich accepts a single parameterframe, which is the interface to the calling object.frame.argsis a table of arguments passed to the function.- Positional arguments are accessed by numeric position.
- Named arguments are accessed by name.
frame:callParserFunction('#time', 'Y-m-d H:i:s')calls the parser function#time, passing the string literal'Y-m-d H:i:s'to display the current time.frame:expandTemplate({title = 'Template:Sandbox', args = {'arg1', 'arg2'}})calls theTemplate:Sandboxtemplate, passing a table of parameter arguments and returns the result.frame:extensionTag('nowiki', '[[text]]', {})tags the given text to control processing when the text is returned to the calling object.frame:getParent()returns the parent of the calling object, or in this case the page that invoked the module.frame:getTitle()returns a string containing the title of the frame.
Conclusion[edit]
Congratulations! You've now created, tested, and understood a Lua script that uses the Frame object. Return to the main Lua page to learn about other Lua code libraries.
See Also[edit]
References[edit]
Title Library
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 use the Lua Title library in your scripts.
Prerequisites[edit]
This lesson assumes you have already completed the Tables lesson.
Create a Lua Script that Uses the Title Library[edit]
To create a Lua script that uses the Title library:
- 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.canTalk(frame) local title = mw.title.getCurrentTitle() return ';canTalk\n:' .. tostring(title.canTalk) .. '\n' end function p.baseText(frame) local title = mw.title.getCurrentTitle() return ';baseText\n:' .. tostring(title.baseText) .. '\n' end function p.exists(frame) local title = mw.title.getCurrentTitle() return ';exists\n:' .. tostring(title.exists) .. '\n' end function p.fileExists(frame) local title = mw.title.getCurrentTitle() return ';fileExists\n:' .. tostring(title.fileExists) .. '\n' end function p.fragment(frame) local title = mw.title.getCurrentTitle() return ';fragment\n:' .. title.fragment .. '\n' end function p.fullText(frame) local title = mw.title.getCurrentTitle() return ';fullText\n:' .. title.fullText .. '\n' end function p.getContent(frame) local text = mw.text.trim(frame.args[1]) local namespace = mw.text.trim(frame.args[2]) local title = mw.title.new(text, namespace) return ';getContent\n<blockquote>' .. title:getContent() .. '</blockquote>\n' end function p.id(frame) local title = mw.title.getCurrentTitle(); return ';id\n:' .. title.id .. '\n' end function p.inNamespace(frame) local title = mw.title.getCurrentTitle(); return ';inNamespace\n:' .. tostring(title:inNamespace(0)) .. '\n' end function p.inNamespaces(frame) local title = mw.title.getCurrentTitle(); return ';inNamespaces\n:' .. tostring(title:inNamespaces(0)) .. '\n' end function p.interwiki(frame) local title = mw.title.getCurrentTitle(); return ';interwiki\n:' .. title.interwiki .. '\n' end function p.isContentPage(frame) local title = mw.title.getCurrentTitle(); return ';isContentPage\n:' .. tostring(title.isContentPage) .. '\n' end function p.isExternal(frame) local title = mw.title.getCurrentTitle(); return ';isExternal\n:' .. tostring(title.isExternal) .. '\n' end function p.isLocal(frame) local title = mw.title.getCurrentTitle(); return ';isLocal\n:' .. tostring(title.isLocal) .. '\n' end function p.isRedirect(frame) local title = mw.title.getCurrentTitle(); return ';isRedirect\n:' .. tostring(title.isRedirect) .. '\n' end function p.isSpecialPage(frame) local title = mw.title.getCurrentTitle(); return ';isSpecialPage\n:' .. tostring(title.isSpecialPage) .. '\n' end function p.isSubpage(frame) local title = mw.title.getCurrentTitle(); return ';isSubpage\n:' .. tostring(title.isSubpage) .. '\n' end function p.isTalkPage(frame) local title = mw.title.getCurrentTitle(); return ';isTalkPage\n:' .. tostring(title.isTalkPage) .. '\n' end function p.isSubpageOf(frame) local title = mw.title.getCurrentTitle(); local text = mw.text.trim(frame.args[1]) local namespace = mw.text.trim(frame.args[2]) local title2 = mw.title.new(text, namespace) return ';isSubpageOf\n:' .. tostring(title:isSubpageOf(title2)) .. '\n' end function p.new(frame) local text = mw.text.trim(frame.args[1]) local namespace = mw.text.trim(frame.args[2]) local title = mw.title.new(text, namespace) return ';new\n:' .. title.id .. '\n' end function p.nsText(frame) local title = mw.title.getCurrentTitle(); return ';nsText\n:' .. title.nsText .. '\n' end function p.prefixedText(frame) local title = mw.title.getCurrentTitle() return ';prefixedText\n:' .. title.prefixedText .. '\n' end function p.rootText(frame) local title = mw.title.getCurrentTitle() return ';rootText\n:' .. title.rootText .. '\n' end function p.subjectNsText(frame) local title = mw.title.getCurrentTitle() return ';subjectNsText\n:' .. title.subjectNsText .. '\n' end function p.subpageText(frame) local title = mw.title.getCurrentTitle() return ';subpageText\n:' .. title.subpageText .. '\n' end function p.text(frame) local title = mw.title.getCurrentTitle() return ';text\n:' .. title.text .. '\n' end return p
Test Your Lua Script[edit]
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|baseText}}
{{#invoke:Sandbox|canTalk}}
{{#invoke:Sandbox|exists}}
{{#invoke:Sandbox|fileExists}}
{{#invoke:Sandbox|fragment}}
{{#invoke:Sandbox|fullText}}
{{#invoke:Sandbox|getContent|Sandbox|Wikiversity}}
{{#invoke:Sandbox|id}}
{{#invoke:Sandbox|inNamespace}}
{{#invoke:Sandbox|inNamespaces}}
{{#invoke:Sandbox|interwiki}}
{{#invoke:Sandbox|isContentPage}}
{{#invoke:Sandbox|isExternal}}
{{#invoke:Sandbox|isLocal}}
{{#invoke:Sandbox|isRedirect}}
{{#invoke:Sandbox|isSpecialPage}}
{{#invoke:Sandbox|isSubpage}}
{{#invoke:Sandbox|isTalkPage}}
{{#invoke:Sandbox|isSubpageOf|Sandbox|Module}}
{{#invoke:Sandbox|new|Sandbox|Module}}
{{#invoke:Sandbox|nsText}}
{{#invoke:Sandbox|prefixedText}}
{{#invoke:Sandbox|rootText}}
{{#invoke:Sandbox|subjectNsText}}
{{#invoke:Sandbox|subpageText}}
{{#invoke:Sandbox|text}}
The result should be similar to:
- baseText
- Sandbox
- canTalk
- true
- exists
- true
- fileExists
- false
- fragment
- fullText
- Module talk:Sandbox
- getContent
- == Welcome == Welcome to the Wikiversity Sandbox. Feel free to experiment with edits on this page.
- id
- 150785
- inNamespace
- false
- inNamespaces
- false
- interwiki
- isContentPage
- false
- isExternal
- false
- isLocal
- true
- isRedirect
- false
- isSpecialPage
- false
- isSubpage
- false
- isTalkPage
- true
- isSubpageOf
- false
- new
- 150784
- nsText
- Module_talk
- prefixedText
- Module talk:Sandbox
- rootText
- Sandbox
- subjectNsText
- Module
- subpageText
- Sandbox
- text
- Sandbox
Understand Your Lua Script[edit]
To understand your Lua script:
local title = mw.title.getCurrentTitle()gets the title object for the current page and assigns it to the variable namedtitle.title.canTalkreturns whether the title can have a talk page.title.baseTextreturns the base title text or parent page text if this is a subpage.title.existsreturns whether the title exists.title.fileExistsreturns whether the file or image exists.title.fragmentreturns the title fragment.title.fullTextreturns the full text of the page title.title:getContent()returns the page content for the title.title.idreturns the title id.title:inNamespace(0)returns whether the title is in the given namespace.title:inNamespaces(0)returns whether the title is in the given namespaces.title.interwikireturns the title interwiki prefix, if any.title.isContentPagereturns whether the title is in a content namespace.title.isExternalreturns whether the title has an interwiki prefix.title.isLocalreturns whether the title is in this wiki project.title.isRedirectreturns whether the title is a redirect.title.isSpecialPagereturns whether the title is a special page.title.isSubpagereturns whether the title is a subpage.title.isTalkPagereturns whether the title is a talk page.title:isSubpageOf(title2))returns whether the title is a subpage oftitle2.mw.title.new(text, namespace)gets the title object for the given page and namespace.title.nsTextreturns the namespace text for the title.title.prefixedTextreturns the title of the page, with the namespace and interwiki prefixes.title.rootTextreturns the title of the root page without prefixes.title.subjectNsTextreturns the text of the subject namespace for the title.title.subpageTextreturns the subpage name for the title.title.textreturns The title text without namespace or interwiki prefixes.
Conclusion[edit]
Congratulations! You've now created, tested, and understood a Lua script that uses the Title library. Return to the main Lua page to learn about other Lua code libraries.
See Also[edit]
References[edit]