Lua/Print version

From Wikiversity
< Lua
Jump to: navigation, search

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:

  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
 
return p

Test Your First Lua Script[edit]

To test your first 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}}

The result should be:

Hello!

Edit Your First Lua Script[edit]

To edit your first Lua script:

  1. Return to the Module:Sandbox.
  2. Edit the line with return 'Hello!' and add your name inside the single quotes. You should end up with something like return 'Hello Lua!'.
  3. Save the page.
  4. 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.
  5. 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.

  1. local p = {} creates a local table or array for your code and names it p.
  2. function p.hello() adds a function named hello to the table. Functions can be invoked (called) by name from outside the module.
  3. return 'Hello!' returns the string Hello! when the function is invoked (called).
  4. end ends the function.
  5. return p returns the code table to whatever process loads this Lua module.

The code that runs the script includes:

  1. #invoke: invokes (calls) a Lua module.
  2. Sandbox specifies the name of the module to be loaded.
  3. hello specifies 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:

  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]

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]

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]

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:

  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]

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]

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]

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:

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

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

  1. local and the following code defines the variables a, b, and result. a and b are initialized. result is nil.
  2. 3 and 2 are numeric literals.
  3. ';Arithmetic\n' is a string literal. String literals may also be defined using double quotes, such as ";Arithmetic\n".
  4. \n is a newline character. Content that follows will appear on a new line in the resulting text.
  5. .. is the concatenation operator. It appends two strings together. Numeric values are automatically converted to strings when concatenated.
  6. +, -, *, and / are add, subtract, multiply, and divide, respectively.
  7. % is the modulo or remainder operator.
  8. ^ is the exponentiation or 'raise to the power of' operator.
  9. - preceding a variable is the negation operator.
  10. == compares for equality.
  11. ~= compares for inequality.
  12. <, >, <=, and >= compare less than, greater than, less than or equal, and greater than or equal, respectively.
  13. tostring() explicitly converts the content to a string. Logical comparisons do not automatically convert to strings.
  14. and returns 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 and stops evaluating as soon as it knows the result is false.
  15. or returns 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 or stops evaluating as soon as it knows the result is true.
  16. not returns the true/false opposite of what follows.
  17. # 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:

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

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

  1. local and the following code defines the variables hour and result. Both are nil.
  2. 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.
  3. tonumber() converts the string to a number.
  4. hour = stores the numeric value of the server time in the variable hour.
  5. if hour < 12 then begins a conditional code block and checks hour to see if it is less than 12. If it is, the following statement(s) are executed. If not, the following statements are skipped.
  6. result = 'Good morning!' sets the value of result.
  7. elseif hour < 18 then checks hour to see if it is less than 18. 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.
    • elseif is optional in a conditional code block and may be repeated.
  8. else indicates 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.
    else is optional in a conditional code block.
  9. end ends the conditional code block.
  10. return result returns 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:

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

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

  1. local and the following code defines the variables i and result. Both are nil.
  2. result = ';for\n' assigns a string literal value to the variable result.
    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.
  3. for i = 2, 10, 2 do creates a loop code block that will vary the value of the variable i from 2 to 10 by 2.
    • 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 do would count down from 10 to 2 by 2.
    • If the increment value is not provided, the default increment is 1. for i = 1, 10 do would count from 1 to 10 by 1.
  4. result = result .. ":i = " .. i .. '\n' concatenates a string literal and the current value of the variable i to result.
  5. end ends the loop.
    The value of the loop variable, i in this case, will be one increment greater than the stop value when the loop ends. In this example, i will be equal to 12 after the loop ends.
  6. return result returns the current value of result as the result of the function.

To understand your Lua script while loop:

  1. local and the following code defines the variables i and result. Both are nil.
  2. result = ';while\n' assigns a string literal value to the variable result.
  3. i = 2 assigns the value 2 to the variable i.
    This could also have been written with the initial variable declaration as local i = 2.
  4. while i <= 10 do creates a loop code block that will loop while the value of i is less than 10.
    • 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.
  5. result = result .. ":i = " .. i .. '\n' concatenates a string literal and the current value of the variable i to result.
  6. i = i + 2 takes the current value of i, adds 2, and stores the result in i.
  7. end ends the loop.
  8. return result returns the current value of result as the result of the function.

To understand your Lua script repeat loop:

  1. local and the following code defines the variables i and result. Both are nil.
  2. result = ';repeat\n' assigns a string literal value to the variable result.
  3. i = 2 assigns the value 2 to the variable i.
  4. repeat creates 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.
  5. result = result .. ":i = " .. i .. '\n' concatenates a string literal and the current value of the variable i to result.
  6. i = i + 2 takes the current value of i, adds 2, and stores the result in i.
  7. until i > 10 sets 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.
  8. return result returns 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 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:

  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 = {}

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:

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

  1. local function toCelsius(f) declares a local function named toCelsius that accepts a single parameter f, which is the Fahrenheit temperature to be converted.
    Declaring the function as local prevents it from being called from outside the module.
  2. return (f - 32) * 5 / 9 converts the Fahrenheit temperature into Celsius and returns the result.
  3. end ends the function.

To understand your Lua script toFahrenheit function:

  1. local function toFahrenheit(c) declares a local function named toFahrenheit that accepts a single parameter c, which is the Celsius temperature to be converted.
    Declaring the function as local prevents it from being called from outside the module.
  2. return c * 9 / 5 + 32 converts the Celsius temperature into Fahrenheit and returns the result.
  3. end ends the function.

To understand your Lua script functions function:

  1. function p.functions() declares a function named functions.
    This function is not declared local, so it can be called from outside the module.
  2. local and the following code defines the variables temperature and result. Both are nil.
  3. result = ';Fahrenheit to Celsius\n' assigns a string literal value to the variable result.
  4. for temperature = 0, 100, 10 do creates a loop code block that will vary the value of the variable temperature from 0 to 100 by 10.
  5. toCelsius(temperature) calls the toCelsius function and passes in the current value of temperature as the temperature to be converted.
  6. string.format() calls the string library format function to format the returned Celsius temperature.
  7. '%.1f' indicates that the resulting format (%) should be a single decimal place (.1) floating point (f) value.
  8. toFahrenheit(temperature) calls the toFahrenheit function and passes in the current value of temperature as the temperature to be converted.
  9. string.format() calls the string library format function to format the returned Fahrenheit temperature.
  10. '%.1f' indicates that the resulting format (%) should be a single decimal place (.1) floating point (f) value.
  11. return result returns the current value of result as 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:

  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 = {}
 
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:

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

  1. local function tableToString(t) declares a local function named tableToString that accepts a single parameter t, which is the table to be converted to a string.
  2. local and the following code defines the variables key, value, and result. All are nil.
  3. result = '' assigns an empty string literal value to the variable result.
  4. for key, value in pairs(t) do creates a loop code block that will vary the value of the variables key and value for each key/value data pair in the table t.
  5. if (tonumber(key) ~= nil) then tests 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).
  6. result = result .. ':table[' .. key .. '] is ' .. value .. '\n' or result = 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.
  7. end ends the loop.
  8. return result returns the current value of result as the result of the function.
  9. end ends the function.

To understand your Lua script sequence function:

  1. function p.sequence() declares a function named sequence.
  2. local numbers = {10, 20, 30} defines a local table variable named numbers, 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.
  3. local result defines the variable result and initializes it to nil.
  4. result = ';sequence\n' assigns a literal string value to the variable result.
  5. result = result .. tableToString(numbers) calls the tableToString function, passing the table numbers as the parameter and concatenates the returned value to the variable result.
  6. return result returns the current value of result as the result of the function.
  7. end ends the function.

To understand your Lua script dictionary function:

  1. function p.dictionary() declares a function named dictionary.
  2. local languages = { and the following code defines a local table variable named languages, 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 as languages['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.key notation, such as languages.en. Quotes around string literal keys are not required with this notation format.
  3. local result defines the variable result and initializes it to nil.
  4. result = ';dictionary\n' assigns a literal string value to the variable result.
  5. result = result .. tableToString(languages) calls the tableToString function, passing the table languages as the parameter and concatenates the returned value to the variable result.
  6. return result returns the current value of result as the result of the function.
  7. end ends 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:

  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 = {}
 
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:

  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:
;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:

  1. local function reciprocal1(value) declares a local function named reciprocal1 that accepts a single parameter value, which is the value whose reciprocal will be returned.
  2. return 1 / value returns the reciprocal of value.
  3. end ends the function.

To understand your Lua script test1 function:

  1. function p.test1(frame) declares a local function named test1 that accepts a single parameter frame, which is the object used to access parameters passed from #invoke.
  2. local value = frame.args[1] defines a local variable named value and assigns the value of the first frame argument (parameter) passed with #invoke.
  3. return reciprocal1(value) calls the reciprocal1 function, passing the variable value and returns the result.
  4. end ends the function.

To understand your Lua script reciprocal2 function:

  1. local function reciprocal2(value) declares a local function named reciprocal2 that accepts a single parameter value, which is the value whose reciprocal will be returned.
  2. if value == nil then creates a conditional code block and tests to see if value is nil. If it is, an error is generated.
  3. error('value must exist') generates an error with the given literal string as the error statement. Using error() 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.
  4. if tonumber(value) == nil creates a conditional code block and tests to see if value is numeric. If it is not, tonumber returns nil and an error is generated.
  5. if tonumber(value) == 0 creates a conditional code block and tests to see if value is 0. If it is, an error is generated.
  6. return 1 / value returns the reciprocal of value.
  7. end ends the function.

To understand your Lua script test2 function:

  1. function p.test2(frame) and the following code declares a local function named test2 that accepts a single parameter frame, which is the object used to access parameters passed from #invoke.
  2. local value = frame.args[1] defines a local variable named value and assigns the value of the first frame argument (parameter) passed with #invoke.
  3. return reciprocal2(value) calls the reciprocal2 function, passing the variable value and returns the result.
  4. end ends the function.

To understand your Lua script reciprocal3 function:

  1. local function reciprocal3(value) declares a local function named reciprocal3 that accepts a single parameter value, which is the value whose reciprocal will be returned.
  2. assert(value, 'value must exist') creates a self-contained conditional code block and tests to see if value is nil If it is, an error is generated.
    It is best practice to use assert to document and test any assumptions that are made regarding passed parameters.
  3. assert(tonumber(value), 'value must be a number') creates a self-contained conditional code block and tests to see if value is numeric. If it is not, tonumber returns nil and an error is generated.
  4. assert(tonumber(value) ~= 0, 'value must not be zero') creates a conditional code block and tests to see if value is 0. If it is, an error is generated.
  5. return 1 / value returns the reciprocal of value.
  6. end ends the function.

To understand your Lua script test3 function:

  1. function p.test3(frame) and the following code declares a local function named test3 that accepts a single parameter frame, which is the object used to access parameters passed from #invoke.
  2. local value = frame.args[1] defines a local variable named value and assigns the value of the first frame argument (parameter) passed with #invoke.
  3. return reciprocal3(value) calls the reciprocal3 function, passing the variable value and returns the result.
  4. end ends the function.

To understand your Lua script test4 function:

  1. function p.test4(frame) and the following code declares a local function named test3 that accepts a single parameter frame, which is the object used to access parameters passed from #invoke.
  2. local value = frame.args[1] defines a local variable named value and assigns the value of the first frame argument (parameter) passed with #invoke.
  3. if pcall(function () result = reciprocal3(value) end) then creates a conditional code block that calls the reciprocal3 function, passing value and storing the result. If no error occurs, result is returned. If an error occurs, a literal string is returned instead.
  4. pcall() uses the pcall (protected call) function to call a function and catch any errors that occur.
  5. function () ... end creates 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 reciprocal3 function while also using pcall() to catch any errors that occur.
  6. end ends 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:

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

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

  1. math.abs(x) returns the absolute value of x returns .
  2. math.acos(x) returns the arc cosine of x (given in radians).
  3. math.asin(x) returns the arc sine of x (given in radians).
  4. math.atan(x) returns the arc tangent of x (given in radians).
  5. math.atan2(y, x) returns the arc tangent of y/x (given in radians), using the signs of both parameters to find the quadrant of the result.
  6. math.ceil(x) returns the smallest integer larger than or equal to x.
  7. math.cos(x) returns the cosine of x (given in radians).
  8. math.cosh(x) returns the hyperbolic cosine of x.
  9. math.deg(x) returns the angle x (given in radians) in degrees.
  10. math.exp(x) returns the value e^x.
  11. math.floor(x) returns the largest integer smaller than or equal to x.
  12. math.fmod(x, y) returns the remainder of the division of x by y that rounds the quotient towards zero.
  13. math.frexp(x) returns two values m and e such that x = m times 2^e, e is an integer, and the absolute value of m is in the range [0.5, 1)
  14. math.huge returns the value representing positive infinity; larger than or equal to any other numerical value.
  15. math.ldexp(m, e) returns m times 2^e (e should be an integer).
  16. math.log(x) returns the natural logarithm of x.
  17. math.log10(x) returns the base-10 logarithm of x.
  18. math.max(x, y) returns the maximum value among its arguments.
  19. math.min(x, y) returns the minimum value among its arguments.
  20. math.modf(x) returns two numbers, the integral part of x and the fractional part of x.
  21. math.pi returns the value of pi.
  22. math.pow(x, y) returns x^y.
  23. math.rad(x) returns the angle x (given in degrees) in radians.
  24. 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.
  25. math.randomseed(os.time()) seeds the random number generator with the current server operating system elapsed time in seconds.
  26. math.sin(x) returns the sine of x (given in radians).
  27. math.sinh(x) returns the hyperbolic sine of x.
  28. math.sqrt(x) returns the square root of x.
  29. math.tan(x) returns the tangent of x (given in radians).
  30. math.tanh(x) returns the hyperbolic tangent of x.

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:

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

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

  1. os.clock() returns the approximate amount of CPU time used by the script.
  2. os.date() returns the current date.
  3. local t1 = {year = 2014, month = 1, day = 1, hour = 0, min = 0, sec = 0, isdst = false} defines a local variable t1 as a table with the given date and time values.
    isdst = false indicates that the time value is not daylight savings time.
  4. local t2 = {year = 2014, month = 12, day = 31, hour = 23, min = 59, sec = 59, isdst = false} defines a local variable t2 as a table with the given date and time values.
  5. os.difftime(os.time(t2), os.time(t1)) returns the difference in seconds between t1 and t2.
  6. 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:

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

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

  1. string.byte('A') returns the numeric ASCII value of the character(s) in the string.
  2. string.char(65) returns the character equivalent of the ASCII value(s) given.
  3. string.find('that', 'at') returns the numeric position of the second string within the first string.
  4. string.format('%.2f', 0) returns the second and any additional parameters formatted based on the first parameter string.
    See fprintf for format specifiers.
  5. for word in string.gmatch('This is a test', '%w+') do processes the first parameter by repeatedly returning a string matching the pattern specified by the second parameter.
    See Patterns for pattern specifiers.
  6. 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.
  7. string.len('len') returns the length of the string.
  8. string.lower('LOWER') returns the string converted to lower case.
  9. 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.
  10. string.rep('*', 5) returns the string repeated the given number of times.
  11. string.reverse('reverse') returns the string reversed.
  12. string.sub('that', 2, 3) returns the substring of the first parameter starting at the second parameter and ending at the third parameter.
  13. 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:

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

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

  1. local function descending(first, second) declares a local function named descending that accepts two parameters, first and second.
  2. 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:

  1. local numbers = {} defines an empty table variable named numbers.
  2. 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.
  3. for i = 1, 10, 1 do creates a loop code block that will repeat 10 times.
  4. table.insert(numbers, math.random(1, 10)) calls the math library random function to retrieve a random number between 1 and 10, inclusive, and then inserts that value into the numbers table.
  5. table.concat(numbers, ', ') retrieves the values in the table numbers and converts them into a string concatenated with ', ' separators between each value.
  6. table.sort(numbers) sorts the numbers table in the default ascending order.
  7. table.remove(numbers, 1) removes the element in position 1 from the table.
    Since the table was sorted prior to removal, this will remove the lowest value from the table.
  8. table.sort(numbers, descending) sorts the table using a custom descending comparison 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:

  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 = {}

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:

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

  1. local function tableToString(t) declares a local function named tableToString that accepts a single parameter t, which is the table to be converted to a string.
    See Lua/Tables for more information.
  2. function p.args(frame) declares a function named args which accepts a single parameter frame, which is the interface to the calling object.
    • frame.args is a table of arguments passed to the function.
    • Positional arguments are accessed by numeric position.
    • Named arguments are accessed by name.
  3. 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.
  4. frame:expandTemplate({title = 'Template:Sandbox', args = {'arg1', 'arg2'}}) calls the Template:Sandbox template, passing a table of parameter arguments and returns the result.
  5. frame:extensionTag('nowiki', '[[text]]', {}) tags the given text to control processing when the text is returned to the calling object.
  6. frame:getParent() returns the parent of the calling object, or in this case the page that invoked the module.
  7. 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:

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

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

  1. local title = mw.title.getCurrentTitle() gets the title object for the current page and assigns it to the variable named title.
  2. title.canTalk returns whether the title can have a talk page.
  3. title.baseText returns the base title text or parent page text if this is a subpage.
  4. title.exists returns whether the title exists.
  5. title.fileExists returns whether the file or image exists.
  6. title.fragment returns the title fragment.
  7. title.fullText returns the full text of the page title.
  8. title:getContent() returns the page content for the title.
  9. title.id returns the title id.
  10. title:inNamespace(0) returns whether the title is in the given namespace.
  11. title:inNamespaces(0) returns whether the title is in the given namespaces.
  12. title.interwiki returns the title interwiki prefix, if any.
  13. title.isContentPage returns whether the title is in a content namespace.
  14. title.isExternal returns whether the title has an interwiki prefix.
  15. title.isLocal returns whether the title is in this wiki project.
  16. title.isRedirect returns whether the title is a redirect.
  17. title.isSpecialPage returns whether the title is a special page.
  18. title.isSubpage returns whether the title is a subpage.
  19. title.isTalkPage returns whether the title is a talk page.
  20. title:isSubpageOf(title2)) returns whether the title is a subpage of title2.
  21. mw.title.new(text, namespace) gets the title object for the given page and namespace.
  22. title.nsText returns the namespace text for the title.
  23. title.prefixedText returns the title of the page, with the namespace and interwiki prefixes.
  24. title.rootText returns the title of the root page without prefixes.
  25. title.subjectNsText returns the text of the subject namespace for the title.
  26. title.subpageText returns the subpage name for the title.
  27. title.text returns 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]