User:Gechy/lua-tutorial

Lua tutorial
The tutorial aims to be accessible to all manner of programmers. Experienced users will read at great speed and beginners can digest the text more slowly; both can take advantage of the examples to clarify. It is thought that learning by example is the best form of learning. Please note that this tutorial assumes you are using Lua version 5.1.

Getting started
You can use the live demo to play with Lua if you don't want to install anything on your computer. For guide on how to install lua on your computer see install lua locally

Setting Up
The software used by Wikipedia, called MediaWiki, has an extension that provides a version of Lua that can be used within Wikipedia pages. The extension is called Scribunto.

For the purpose of this tutorial, the examples can be run in lua demo site. The print function is not available in Scribunto. See the example:

An equivalent of the code snippet above using the print function is shown below

The MediaWiki libraries are only implemented in Scribunto. See running lua code in wikipedia

Lua variable type
The variable name is the usual way to reference the stored value, in addition to referring to the variable itself, depending on the context. There are eight basic types of values in Lua: number, string, boolean, table, function, nil, userdata, thread. In Scribunto we make use of six out of the eight types available in the Lua programming language.

Numbers
The number type represents a floating-point (fractional) number. They represent real (double-precision floating-point) numbers.

Arithmetic operation with numbers
Lua allows simple arithmetic on numbers using the usual operators to add, subtract, multiply and divide.

From the example above, you observed that the numbers are not rounded into integers. They are floating point, or real numbers.

Assignment operator
In Lua, we can assign values to variables using the = operator.

From the example above, we can now use the value in x for other arithmetic operations.

String
Lua also uses strings (i.e. text) types. To create strings, wrap text in "double quotes" or 'single quotes'. Strings in Lua can contain any 8-bit value, including embedded zeros, which can be specified as '\0'.

In lua strings can be assign to a variables just like we can for numbers:

Lua string concatenation is done using the .. operator and not the + operator shown below:

Boolean
Boolean values have either the value true or false. The not operator can be placed before a boolean value to invert it.

Boolean values are used to represent the results of logic tests. The equals ==, and not equal ~= operators will return boolean values depending on the values supplied to them

Note that for an assignment you use a single equals sign (=), but for comparison, you use a double equals sign (==). As shown in the examples above.

Tables
Lua has a general-purpose aggregate data type called a table. Aggregate data types are used for storing collections (such as lists, sets, arrays, and associative arrays) containing other objects (including numbers, strings, or even other aggregates).

Tables are created using a pair of curly brackets {}.

It is normal if your table does not have the same unique identifier as in the above example.

Function
In Lua, functions are assigned to variables, just like numbers and strings. Functions are created using the function keyword. It allows you to call the same code in multiple places. Lets create a simple function to print hello:

You will notice that we could print the value of the variable foo (like tables). The value is a function with a unique identifier. A function can be assigned to a variable:

From the example above, in lua all values are treated the same way (first-class values).

nil
nil is a special value which indicates the lack of a useful value. If you try getting a variable that doesn't exist you will get nil:

userdata
Userdata values are objects foreign to Lua, such as objects implemented in C. These typically come about when an object in a C library is exposed to Lua.

thread
A thread value represents an independent (cooperative) thread of execution.

Dynamic typing
Lua has dynamic typing. This means that types are checked while a program is running. Like many other programming languages with dynamic typing, in Lua you don't have to specify what type a variable is. The variable knows what type it is from the value, or object, assigned to it.

Lua we can also assign different types of values to the same variable, e.g.

Querying type
You can use the Lua function  type to get a description of the type of a particular object.

Assignment statement
Setting the value of a variable is an assignment:

Multiple assignment
In Lua you can perform multiple assignments in a single statement, e.g.,

The list of values on the right is assigned to the list of variables on the left of the =. We can assign as many values as we like and they don't all have to be of the same type as seen in the example above.

However, multiple assignments come with a few limitations as described below:

Evaluation occurs before an assignment
Any expressions are evaluated first. The evaluated expression is then assigned.

When Lua reaches the second line it evaluates the expressions i+1 and i before anything else. After evaluation the second line becomes i, x = 8, 7. Then it performs the assignments from right to left.

Swapping values
you can use multiple assignments to swap variable values around:

Note that there is no need for a temporary variable (such as bold = b; b = a; a = bold;).

Assignment order
The order in which multiple assignments are performed is not defined. This means you shouldn't assume the assignments are made from left to right. If the same variable or table reference occurs twice in the assignment list the results may surprise you.

In the above example, Lua does assignments from right-to-left, e.g. a=2 and then a=1. You should use separate assignment statements if the order of assignment is important to you.

Mismatched list sizes
If a value list is longer than the variable list the extra values are ignored.

Lua assigns the value nil to the variables without a value if a value list is shorter than the variable list.

Number manipulations
Lua supports only one type of number: floating-point number. By default, these are floating-point numbers. However, Lua can easily be recompiled to support single-precision floating-point numbers should you so desire.

If you use numbers with fractional parts (or division), they may have a rounding error. Numbers which have infinitely repeating patterns in decimal will not have them in binary, so don't assume that any fractional number is safe.

You don't use the == operator with fractional numbers since it checks for perfect equality. Remember to write your code in such a way that rounding error don't build up over time.

When your numbers are integers (with no fractional part), and they don't reach 2^53; then you won't need to worry about these issues.

Performing calculation in lua
We can use the Lua interactive command-line prompt as a calculator by prefixing an expression by =. This can be performed also on lua demo

Lua also understands exponent types for expressing numbers in the form e or E, which represents * 10 ^.

You can assign numbers to variables and do arithmetic:

Number conversion
You can convert strings to numbers using the function tonumber. This takes a string argument and returns a number.

For converting integers to floating points, this calculation returns a decimal format of the converted integer:

Coercion
Lua will automatically convert string and number types to the correct format to perform calculations. if you try to apply an arithmetic operation to a string Lua will try to convert that string to a number first. Otherwise, the operation will not work. This automatic conversion of types is called coercion.

You can see the calculation succeeds where a string was converted to a number. The string "hello" cannot be converted to a number and so an error occurs. This works in Lua because it is dynamically typed.

A notable exception: comparison operators (== ~= < > <= >=) do not coerce their arguments. Ordered comparison operators throw an error when you feed them different types.

For performance reasons, you should avoid relying on automatic coercion too much. Make sure that all numbers in performance-sensitive computations (especially in inner loops) are of the proper type.

String
Strings can be defined using single quotes, double quotes, or double square brackets.

You can enclose one type of quotes in the other. e.g..

Double bracketed strings also have a few other special properties.

Escape sequences
Lua can also handle C-like escape sequences. Escape sequences are not recognized when using double brackets, so:

Multiline quotes
Double square brackets can be used to enclose literal strings which traverse several lines. e.g.,

Nesting quotes
Double square brackets allow nesting, but they require one or more = inserted in the outer-most brackets to distinguish them. It doesn't matter how many = are inserted, as long as the number is the same in the beginning and ending brackets.

Concatenation
Strings can be joined together using the concatenation operator "..". e.g.,

Numbers can be concatenated to strings. In this case, they are coerced into strings and then concatenated. You can read more about coercion below

Doing a large number of concatenation operations may be slow because each concatenation may allocate a new string in memory.

Coercion in string
Lua performs automatic conversion of numbers to strings and vice versa where it is appropriate. This is called coercion.

As shown above, during coercion, we do not have full control over the formatting of the conversion. To format the number as a string as we would like we can use the string.format function. e.g.,

This is an explicit conversion using a function to convert the number, rather than coercion.

String library
Lua supplies a range of useful functions for processing and manipulating strings in its standard library. Below are a few examples of usage of the string library.

Lua expressions
Expressions are evaluated in order to perform calculations which may assign values to variables or pass arguments to functions.

We'll use the = expression shorthand notation for this page. The values can easily be assigned to a variable, e.g.,

Arithemetic expressions
Lua has the usual binary arithmetic operators.


 * Unary negation:


 * Modulo (division remainder):

Control statement
Control structures let your program make choices, or to run the same piece of code many times.

if statement
The if statement lets you run different code based on a condition:

The if and else if parts are checked in order, and once one of the conditions is true, it runs the block under it and skips to the end, ignoring any other else if conditions after it. The else block is run if none of the conditions matches. Finally, the else if and else parts are optional.

For more complex example:

You noticed how just one of the messages is printed, even though more than one of the conditions are true: This is because once one matches, the if statement skips checking the other conditions.

while loop
This runs the block over and over in a loop on each iteration. It checks the conditions and if it's false, skips to the end and breaks the loop. If the condition is always false, the block will never run.

repeat loop
This is same as the while loop, except the condition is inverted(breaks the loop when true).

Its checks after the first iteration, so the code is guaranteed to run at least once.

numeric for loop
Runs the block with a variable first being equal to start, then keeps incrementing it step amount and running the block again until it's greater than stop. step can be omitted and will default to 1.

You can also make the step negative, and the loop will stop once the counter variable is less than the stop value.

Also, remember that the variable in a for loop is only visible inside the block.

iterator for loop
The iterator version of the for loop takes a special iterator function and can have any amount of variables.What the loop does and how many variables it needs depends on the iterator. see example below:

The ipairs is the iterator, which gets the numbered entries from a table in order.

break statement
The break statement causes Lua to jump out of the current loop: With nested loops, break only affects the innermost one: Using break outside of a loop is a syntax error:

Conditions
Conditions don't necessarily have to be boolean values. In fact, any value is a valid condition: nil and false make the condition false, anything else (including 0) makes it true.

In lua assignment is a statement and not an expression. See below example for syntax error:

if/else as an expression
Lua doesn't have a ternary operator that acts like an if/else statement, but in many cases, you can imitate it using the and and or logical operators. This works for two reasons:
 * Those operators don't even run the right-side expression if the logical result is known only from the left side result
 * They directly return the result of their sub-expressions, instead of converting them to boolean:

This can be used to make a simple if/else expression:

Also remember that and has a higher precedence than or. if the condition is false, it makes the and expression give up and return false.This then makes the or part try its right-side expression and return its value. If the condition is true, and will return its right-side expression. This is then given to or, which sees that the left result is a true condition, and just returns it.

Note that we assumed that the result of the true branch is a value that acts as a true condition. This leads to the catch: the true branch cannot evaluate to nil or false because then the false branch will also be run and its value will be returned:

This is because the whole "and" sub-expression is now false, causing "or" to try running its other sub-expression. But it is alright to return a false value from the false branch. In fact, if you're in a situation like the above example, you can just invert the condition and swap the contents of the branches:

But if both branches must return a value that acts like a false condition, there's no way to work around that.

An if statement can be followed by an optional else if...else statement, which is very useful to test various conditions using single if...else if statement.

While using if, else if, else statements, there are a few points to keep in mind


 * An if can have zero or one else's and it must come after any else if's.


 * An if can have zero to many else if's and they must come before the else.


 * Once an else if succeeds, none of the remaining else if's or else's will be tested.

When you build and run the above code, it produces the following result.

Lua tables
Tables are the only "container" type in Lua.They are associative arrays, which means they store a set of key/value pairs. In a Key/Value pair you can store a value under a key and then later retrieve the value using that key.

Creating tables
Tables are created using table constructors, which are defined using curly brackets, e.g. { }. To define an empty table we can do the following.

Notice when the value of a table is displayed only the type and unique id of the object are displayed. To print out the contents of a table we must do so explicitly.

Using tables
To access the value associated with the key in a table you can use the table[key] syntax:

if there's no value associated with the key, its not an error, instead the result will be nil:

You can erase a key/value pair from a table by assigning nil to the value.

You can use any value can be used as a key (not just numbers and strings) just make sure it's not nil or NaN (Not a Number):

It's so common to use string constants as keys there's a special shortcut syntax for it:

The shortcut syntax is only valid if the string consists of underscores, letters, and numbers, but shouldn't start with a number.

You can also add key/value associations right inside the {} syntax:

There is also a syntax shortcut for string keys in {}, as long as the string conforms to the same rules as the . syntax:

To loop over all the key/value pairs in a table, use the pairs iterator:

The order when looping with pairs is undefined. Just because you added one item after adding another doesn't mean that's the order they'll be in with pairs.

Inside a pairs loop, it's safe to reassign existing keys or remove them (by assigning nil to them), but not to add new keys (that had a nil value previously).

Tables as arrays
Tables are still just key/value containers because Lua doesn't actually have an array type. But tables can be treated like arrays which are explained here:

Table constructors can contain a comma-separated list of objects to create an "array":

This is a syntax shortcut for:

Note it's still just a key/value association.

You can also mix the array syntax with the usual key=value syntax:

The first index is the number one, unlike most other languages that start with the number zero. The reason this was chosen is that it's often more intuitive. It was also chosen because it's just a key and not an offset from the beginning.

You can get the "length" of an array using the # operator: The # operator doesn't count all the items in the table (!). Instead, it finds the last integer (non-fractional number) key. Because of how it's implemented its results are undefined if all the integer keys in the table aren't consecutive. Which is why it shouldn't be used for tables used as sparse arrays).

There are two ways to add an item to the end of an array:

table.insert takes an optional index parameter to insert into the middle of an array. It shifts up any other integer keys above the index: table.remove removes an item from an array, shifting down any remaining integer keys:

To loop over an array use ipairs. Unlike pairs it only gives you the consecutive integer keys from 1. It guarantees their order sequence. With pairs the number keys will not necessarily be given in the correct order!

To join together an array of strings there's table.concat. It takes an optional separator, starts, and end parameters. Here we only use the separator:

Table values are references
In lua when you pass a table to a function or store it in a new variable, etc. a new copy of that table is not created. Tables do not act like numbers in these cases. Instead, the variable or function becomes a reference to the original table.

Tables are freed from memory by the garbage collector after the last reference to them is gone. This does not always happen immediately, however. The garbage collector is designed to work correctly even if a table (directly or indirectly) contains a reference to itself.

Comparing tables using == will return false even if the two tables have the same contents. They must actually be references to the same table. Table comparison works by reference.

If you want to copy a table you'll have to do it manually. Lua offers no standard function for it mainly due to all the different ways you can copy a table.

Tables as unordered sets
Often people new to Lua will create an array to store a group of objects even if the order isn't necessary. The problem with this is that removal is slow because the computer needs to shift down other items. Checking if an item is in the array is slow; again because the computer must loop over all the items.

This can be solved by storing items in the keys and setting values to a dummy value (like true). Doing that will help you use a table like an unordered set with fast insertion, removal, and lookup.

The main differences are that there's no easy way to get the count (you have to use a loop), and you can't store the same item twice in the set.

So if you need to store a group of items it's best to consider both sets and arrays to see what fits your situation best.

Introduction to functions
Functions let you store a piece of code in a value. They are useful to be able to run the same piece of code from multiple places, without having to duplicate it. Also, they let you change the behaviour of your program at runtime by giving different functions to different parts of your code.

Defining functions
Functions are created with the function keyword as follows:

function ( args ) body end

The following example shows a simple function that receives a single argument and returns twice its value: The arguments (also known as parameters) are specified inside the part, and values are returned from the function using the return keyword. Without the return, the function would return no values.

Functions are values
Notice that in the above example, we didn't actually "name" the function, we just assigned it to a variable. This is because in Lua functions are regular values (like numbers, strings, tables, etc.), and you can do anything with them that you can do with any other value.

The function' block is an expression (in the same sense that "1 + 2" is an expression) that evaluates to a new function value. A function value can be called by using the operator, which runs the code in the function. The pair goes after the function expression, and optionally contains a comma-separated list of arguments.

This means that Lua functions are considered anonymous (no pre-set name), and first-class (not treated differently from other values).

Functions are passed by reference. if you assign a variable containing a function to another variable, you just create a new "handle" to the same function.

Function arguments
Functions can take 0 or more arguments. These are values given to the function when it's called, that the code stored in the function can use. parameters look like a variable but they only exist inside the function. see below example:

Function return values
Functions can also return values back to the code that called them using the return keyword. In lua function can return any amount of values. To use this, put comma-separated values after the return keyword:

One thing to remember about the last example ( {f} ) is that if the function returns nils, since nil in tables is considered "no value",, the # operator can't be reliably used to get the number of values because it's undefined if an array has "holes".

Lua functions actually return separate values, instead of a single container.


 * Return skips other code. see example below

Using functions as parameters and returns
Functions as parameters or using them as return values is a useful feature because it lets you plug in your own behaviour into existing code. One good example is table. sort, which can optionally take a custom "less than" function:

Variable number of arguments
A function can have ... at the end of its argument list. This will capture any remaining args passed after the named ones. Then you can use ... inside the body of the function, and it will evaluate to the multiple values (with the same rules as functions call with multiple returns).

For example, a function that passes its extra args unchanged to another function:

To get a specific item from ..., use the select function, which takes a number and a variable number of args, and returns the args starting from that index. It can also take "#" as the index and return the amount of args:

... can also be packed into a table:

A table with array items can also be "unpacked" to an arg list:

But in the second example, we see a problem: tables can't store nil, which means that the # operator (which table.unpack uses internally) can't be used, since it's undefined if the array has nil "holes". Even looping over the table to find the item with the biggest key won't get the real length if nil was the last arg to the function.

Named functions
Although Lua lets us use functions freely like any other value, we will usually just want to give them a name (by storing them in a variable) and use them by that name. Lua has some syntax sugar to make storing a function in a variable look nicer:

Generally, it is recommended to use the shortcut syntax in real scripts unless there's no reason to give your function a name.

Also, there is similar syntax for storing functions in tables:

Lua scope
Until now you just assigned values to names and could get back the value by using the name anywhere in the script. This is fine for small examples, but now that you know functions, it can be a big problem: what if different functions use the same name to store temporary values? They will conflict and overwrite each other, making your script an impossible-to-debug mess. The solution is to control where your variables exist using the local keyword.

Creating local variables
To create local variables, add the local keyword before the assignment:

You don't need the local keyword any more when changing the variable:

Local variables only exist in the block they were created in. Outside of the block, they do not exist any more.

The place where a variable is visible is called the "scope" of a variable.

Now let's use functions to show how this is really useful:

As you can see, each variable is visible from the point where it's declared to the end of the block it's declared in. Even though bar's x exists at the same time as foo's x, they're not written in the same block, so they're independent. This is what's called lexical scoping.

Local function
From the example above, if the contents of the function used f to get a reference to itself, it will correctly get the local variable in the first and second versions, but the third version will get the global f (which will be nil, if not a completely unrelated value set by some other code).

Closures
Functions can use local variables created outside of them. These are called upvalues. A function that uses upvalues is called a closure:

The function sees the change even if it's changed outside of the function. This means that the variable in the function is not a copy, it's shared with the outer scope.

Also, even if the outer scope has passed, the function will still hold on to the variable. If there were two functions created in the scope, they will still share the variable after the outer scope is gone.

Since the two values returned by the two calls to f are independent, we can see that every time a function is called, it creates a new scope with new variables.

Similarly, loops create a new scope on each iteration:

Usage

 * Why are local variables difficult in the interactive interpreter 

This is because it runs each line in a new scope:

One thing you can do is wrap the code in a do-end block, but it won't be interactive until you finish writing the whole block:


 * Why not local by default?

The problem with changing the outer one is that you might have intended to make a new variable, and instead change the existing one that you might not even know about, introducing bugs.

The problem with creating a new one is what if you actually want to change the outer one?

With the local keyword, it's all explicit: without local, you change the existing variable, with it, you create a new one.


 * When to use local variables

The general rule is to always use local variables unless it's necessary for every part of your program to be able to access the variable (which is very rare).

Since it's easy to forget a local, and since Lua doesn't warn you about it (instead silently creating a global), it can be a source of bugs. One solution is to use a script like strict.lua (shown below), that uses metatables to trap global variable creation and raise an error. You can put the script in a file in your project, and do require("strict") to use it.

Lua metamethods
Lua has a powerful extension mechanism which allows you to overload certain operations on Lua objects. Each overloaded object has a metatable of function metamethods associated with it.

A metatable is a regular Lua table containing a set of metamethods, which are associated with events in Lua. Events occur when Lua executes certain operations, like addition, string concatenation, comparisons etc. Metamethods are regular Lua functions which are called when a specific event occurs. The events have names like "add" and "concat" which correspond with string keys in the metatable like "__add" and "__concat".

Metatables
We use the function setmetatable to make a table act as a metatable for a certain object.

When the addition operator finds that its operands aren't numbers, it tries checking if one of them has a metatable with an __add key. In this case it does, so it runs the function stored under that key in the metatable, equivalent to this:

Metatables are still triggered with math operators if one of the operands is a number. And the left operand is always the first parameter to the function, and the right operand is always the second. This means that the table that has the metamethod might not necessarily be the first parameter to the metamethod.

Metamethod types
Below are some metamethod events that lua handles.

__index
This is a very commonly used and versatile metamethod, you run a custom function or use a "fallback" table if a key in a table doesn't exist. If a function is used, its first parameter will be the table that the lookup failed on, and the second parameter will be the key. If a fallback table is used, remember that it can trigger an __index metamethod on it if it has one, so you can create long chains of fallback tables.

__newindex
This metamethod is called when you try to assign to a key in a table, and that key doesn't exist (contains nil). If the key exists, the metamethod is not triggered.

Comparison operators
__eq is called when the == operator is used on two tables, the reference equality check failed, and both tables have the same __eq metamethod (!).

__lt is called to check if one object is "less than" another. Unlike __eq, it's not an error if the two objects have different __lt metamethods, the one on the left will be used.

That's all you need for all of the comparison operators to work with your object. But there will be some cases where both __lt and __eq will need to be called by the same operator. To avoid this, you can optionally add the __le (less than or equal to) metamethod. Now only one of the metamethods will be called with any of the comparison operators.

__metatable
__metatable is for protecting metatables. If you do not want a program to change the contents of a metatable, you set its __metatable field. With that, the program cannot access the metatable (and therefore cannot change it). see this for a list of all metamethods Metatable and metamethods

Lua environments
Unlike local variables, which are stored in a special data structure in the interpreter, global variables are just stored in a table. Each function has an environment table associated with it, that can be manipulated with the getfenv/setfenv standard functions.

getfenv and setfenv both take a function or stack level (where 1 is the current function, 2 is the function that called the current function, etc.). setfenv has a second parameter that takes the new env table, and getfenv returns the functions's current env table.

Creating and using modules
Lua 5.0 and 5.1 have a module function that's used like this:

And it would be used like this:

The way it works is it creates a new table for the module, stores it in the global named by the first argument to module, and sets it as the environment for the chunk, so if you create a global variable, it gets stored in the module table.

Core functions
These functions provide access to the core functionality of Lua.

Assert(test, [message])
assert is similar to the assert function in C. If the test condition is false or nil an error is raised; otherwise test is returned. An optional user-defined message is included in the error raised. Also, see the error function. E.g.,

Many Lua functions, such as io.open, return a value on success, or return nil and an error message on failure. This works well with assert:

This either opens filename for reading and assigns it to file, or it raises an error with the message in the second return value from io.open.

dofile(filename)
It opens the file and executes the contents of the file as a chunk. If no parameter is passed, then this function executes the contents of standard input. The errors will be propagated to the caller.

error (message[,level])
Errors may be "thrown" using the error and assert functions. To "catch" errors, use pcall or xpcall. Note that certain internal Scribunto errors cannot be caught in Lua code.

_G
_G is a global variable which points to the global environment. For example to display all of the globals variables we might do the following:

Lua itself does not use this variable, so changing its value does not affect any environment. You should use setfenv to change environments.

getfenv(f)
Returns the current environment in use by the function. f can be a Lua function or a number that specifies the function at that stack level: Level 1 is the function calling getfenv. If the given function is not a Lua function, or if f is 0, getfenv returns the global environment. The default for f is 1.

getmetatable(object)
If the object does not have a metatable, returns nil. Otherwise, if the object's metatable has a "__metatable" field, returns the associated value. Otherwise, returns the metatable of the given object.

ipairs(t)
This functions fetches the indices and values of tables.

load(func [, chunkname])
Loads a chunk using function func to get its pieces. Each call to func must return a string that concatenates with previous results.

loadfile(filename)
Similar to load, but gets the chunk from file filename or from the standard input, if no file name is given.

loadstring(string [, chunkname])
Similar to load, but gets the chunk from the given string.

next(table [, index])
Allows a program to traverse all fields of a table. Its first argument is a table and its second argument is an index in this table. next returns the next index of the table and its associated value.

pairs(t)
Suspends the running coroutine. The parameter passed to this method acts as additional return values to the resume function.

print(e1, e2, ...)
print can be passed any number of comma-separated arguments which it prints the values of to stdout. print uses tostring to convert the arguments into string form to be printed. E.g.

print is very simple and will not recurse into tables printing the content, it will just print the type and a unique id.

print does not format text. In order to do this, you should use the string.format function in conjunction with print. E.g

tostring(e)
tostring converts its argument (just its first argument if there is more than one) to a string and returns that string. print is implemented using tostring so you are probably already familiar with the output format. Simple values (numbers, strings, booleans, and nil) are converted as you probably expect. Tables, Userdata, and Threads, are printed as `table:', `userdata:', or `thread:', followed by the address of an internal interpreter object (which should on no account be relied upon).

Note that unlike print, tostring doesn't print anything, it just converts its argument to a string and returns it.

tostring's behaviour is extensible. If the value to be converted has a metatable with a __tostring entry then that entry is called with the value to be converted and the result of that call is returned. This allows you to change how tostring works on (certain) tables, by giving them a metatable with a __tostring function that performs the conversion that you want.

type(v)
type returns a string describing the type of the object passed to it.

Note, the type of nil is "nil".

unpack(list)
unpack takes the elements of a list and returns them, e.g.:

The number of elements unpacked is defined by the size of the table, which is not necessarily the number of elements in the table

__Version
_VERSION is "a global variable (not a function) that holds a string containing the current interpreter version."

xpcall(f,err)
Certain internal errors cannot be intercepted.

rawget(table, index)
Gets the real value of table[index], without invoking any metamethod. the table must be a table; index may be any value.

rawequal(v1, v2)
Checks whether v1 is equal to v2, without invoking any metamethod. Returns a boolean.

rawset(table, index, value)
Sets the real value of table[index] to value, without invoking any metamethod. the table must be a table, index any value different from nil, and value any Lua value. This function returns the table.

require(packagename)
Can fetch certain built-in modules distributed with Scribunto, as well as modules present in the Module namespace of the wiki. To fetch wiki modules, use the full page name including the namespace. Cannot otherwise access the local filesystem.

setfenv(f, table)
Sets the environment to be used by the given function. f can be a Lua function or a number that specifies the function at that stack level − Level 1 is the function calling setfenv. setfenv returns the given function. As a special case, when f is 0 setfenv changes the environment of the running thread. In this case, setfenv returns no values.

select(index, ...)
If index is a number, returns all arguments after argument number index. Otherwise, index must be the string "#", and select returns the total number of extra arguments it received.

tonumber(e [, base])
Tries to convert its argument to a number. If the argument is already a number or a string convertible to a number, then tonumber returns this number; otherwise, it returns nil.

MathLibrary
Below is a summary of the functions and variables provided.

math.abs
Return the absolute, or non-negative value, of a given value.

math.acos
Return the inverse cosine in radians of the given value.

math.asin
Return the inverse sine in radians of the given value.

math.atan
Return the inverse tangent in radians. You can do this by supplying y/x yourselves or we can pass y and x to math.atan to do this for us.

Using two arguments should usually be preferred, particularly when converting rectangular co-ordinates to polar co-ordinates. It will use the sign of both arguments to place the result into the correct quadrant, and also produces correct values when one of its arguments is 0 or very close to 0.

math.ceil
Return the integer no less than the given value (even for negatives).

math.cos
Returns the cosine value for a given value in radians.

math.deg
Convert from degrees to radians

math.exp
math.exp(myval) returns e (the base of natural logarithms) raised to the power myval.

math.floor
Return the integer no greater than than the given value (even for negatives).

math.huge
math.huge is a constant. It represents +infinity.

Note that some operations on math.huge return a special "not-a-number" value that displays as nan. This is a bit of a misnomer. nan is a number type, though it's different from other numbers:

math.log
math.log returns the inverse of this. math.exp(1) returns e.

math.max
Return the maximum value from a variable length list of arguments.

math.min
Return the minimum value from a variable length list of arguments.

math.modf
Return the integral and fractional parts of the given number. If you want the modulus (remainder), look for the modulo % operator instead.

math.pi
This is a part of the constant Pi.

math.random
math.random generates pseudo-random numbers uniformly distributed. Supplying argument alters its behaviour:
 * math.random with no arguments generates a real number between 0 and 1.
 * math.random(upper) generates integer numbers between 1 and upper (both inclusive).
 * math.random(lower, upper) generates integer numbers between lower and upper (both inclusive).

upper and lower must be integer. In other case Lua casts upper into an integer, sometimes giving math.floor(upper) and others math.ceil(upper), with unexpected results (the same for lower).

math.randomseed
The math.randomseed function sets a seed for the pseudo-random generator: Equal seeds produce equal sequences of numbers.

A good* 'seed' is os.time, but wait a second before calling the function to obtain another sequence! To get nice random numbers use:

math.sin
Returns the sine value for a given value in radians.

math.tan
Returms the tangent value for a given value in radians.

StringLibrary
In Lua string indices start at index value 1(as they do in C), not index value 0 and they can be negative. Negative indices are indices that has the reverse order. For instance, -2 of "miner" is "e", thus, -1 is #s(s is the string)

string.byte(s [, i[, j]])

 * s:byte([i [, j]])

Return the numerical code(You can search the list of numerical codes ) of s[i] to s[j] of the string passed.

string.char(i1, i2, ...)
Generate a string representing the character codes passed as arguments. Numerical codes are not necessarily portable across platforms.

string.dump(function)
Returns a binary representation of the given function, so that a later load string on that string returns a copy of the function. The function must be a Lua function without upvalues.

string.find(s, pattern [, index [, plain]])
Find the first occurrence of the pattern in the string passed. If an instance of the pattern is found a pair of values representing the start and end of the string is returned. If the pattern cannot be found nil is returned.

We can optionally specify where to start the search with a third argument. The argument may also be negative which means we count back from the end of the string and start the search.

string.format(s, e1, e2, ...)
Create a formatted string from the format and arguments provided. This is similar to the printf("format",...) function in C. An additional option %q puts quotes around a string argument's value.


 * A, a, c, d, E, e, f, G, g, i, o, u, X, and x all expect a number as an argument.


 * q and s expect a string.

string.gmatch(s, pattern)
This returns a pattern finding iterator. The iterator will search through the string passed looking for instances of the pattern you passed.

string.gsub(s, pattern, replace [, n])
This is a very powerful function and can be used in multiple ways. Used simply it can replace all instances of the pattern provided with the replacement. A pair of values is returned, the modified string and the number of substitutions made. The optional fourth argument n can be used to limit the number of substitutions made:

Just like string.find we can use patterns to search in strings. If a capture is used this can be referenced in the replacement string using the notation %capture_index

If the replacement is a function, not a string, the arguments passed to the function are any captures that are made. If the function returns a string, the value returned is substituted back into the string.

string.len(s)
Return the length of the string passed.

string.lower(s)
Make uppercase characters lower case.

string.match (s, pattern [, index])
Extract substrings by matching patterns.

string.rep(s, n)
Generate a string which is n copies of the string passed concatenated together.

string.reverse(s)
Reverses a string.

string.sub(s, i [, j])
Return a substring of the string passed. The substring starts at i. If the third argument j is not given, the substring will end at the end of the string. If the third argument is given, the substring ends at and includes j.

string.upper(s)
Make all the lower case characters upper case.

TableLibrary
Most functions in the table library assume that the table represents an array or a list. For these functions, when we talk about the "length" of a table we mean the result of the length operator [i.e. #].

table.concat(table [, sep [, i [, j]]])
Concatenate the elements of a table to form a string. Each element must be able to be coerced into a string. A separator can be specified which is placed between concatenated elements. Additionally a range can be specified within the table, starting at the i-th element and finishing at the j-th element.

concat will fail on a table that contains tables because they cannot be coerced into strings.

table.sort(table [, comp])
Sort the elements of a table in-place (i.e. alter the table).

If the table has a specified size only the range specified is sorted, e.g.,

A comparison function can be provided to customise the element sorting. The comparison function must return a boolean value specifying whether the first argument should be before the second argument in the sequence. The default behaviour is for the < comparison to being made. For example, the following behaves the same as no function being supplied:

You can see if we reverse the comparison the sequence order is reversed.

table.insert(table, [pos,] value)
Insert a given value into a table. If a position is given insert the value before the element currently at that position:

If no position is specified we append the value to the end of the table:

When a table has an element inserted both the size of the table and the element indices are updated:

When no position is specified the element is inserted at the end of the table according to the calculated size. The size of a table may be user-specified and not reflect the number of elements, e.g.,

table.remove(table [, pos])
Remove an element from a table. If a position is specified the element at that the position is removed. The remaining elements are reindexed sequentially and the size of the table is updated to reflect the change. The element removed is returned by this function. E.g.,

If no position is given remove the last element in the table which is specified by the size of the table. E.g., If the size of the table does not reflect the number of elements nothing is removed, e.g.,

Note that table.remove only works with numeric indexes. For dictionaries you can just unset tables entries with tablevariable["index"] = nil;

OsLibrary
You can find details about the operating system library.

os.clock
Return CPU time since Lua started in seconds.

os.date([format [, time]])
Return formatted date string, or table of time information. The format string has the same format as the C strftime function.

Simple example:

If the format string is "*t" a table is returned containing the time information, e.g,

Above example using pairs method:

If the format is preceeded by "!" the time is converted to Coordinated Universal Time, e.g.,

os.execute([command])
Execute an operating system shell command. This is like the C system function. The system-dependent status code is returned.

With no argument, this command returns a non-zero value if an OS shell is presents or a zero value if one is not present.

os.exit([code])
Calls the C function exit, with an optional code, to terminate the host program. The default value for code is the success code.

os.getenv(varname)
Returns the value of the process environment variable varname, or nil if the variable is not defined.

os.remove(filename)
Deletes the file with the given name. If this function fails, it returns nil, plus a string describing the error.

os.rename(oldname, newname)
Renames file named old name to newname. If this function fails, it returns nil, plus a string describing the error.

os.setlocale(locale [, category])
The function returns the name of the new locale, or nil if the request cannot be honoured.

os.time([table])
Given a formatted date table, as used by os.date return the time in system seconds.

os.tmpname
Generate a name that can be used for a temporary file. This only generates a name, it does not open a file.