Jump to content

User:Gechy/lua tutorial

From Wikipedia, the free encyclopedia
This is an old revision of this page, as edited by Gechy (talk | contribs) at 21:23, 17 December 2020 (Arithemetic expressions). The present address (URL) is a permanent link to this revision, which may differ significantly from the current revision.

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

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.

print(2+2)    -- Addition of numbers

4              -- Output
print(2-7)    -- Subtraction operation 

-5            -- Output
print(7*8)    -- Multiplication operation

56            --Output
print(7/8)    --Division operation

0.875        --Output

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.

 x = 7     -- = operator assigns the number 7 to the variable x.
 print(x)   --  function again to print out the value of x
 7             -- output

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

 x = x * 9  
 print(x)
 63
 print(x*2) -- will not change the value of x
 126
 print(x)
 63       -- new value for X

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

print("hello")  -- quoted string
hello          -- output

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

 name = "John"
 print(name)
 John

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

print("hello " .. name) -- the variable "name" was assigned above
hello John              -- output

Boolean

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

 x = true   -- assign true to the variable
 print(x)   -- invoking the print function
 true       -- output
 print(not x)   -- using the not operator
 false          --  inverted output
 print(not false)
 true       -- inverted output

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

 print(1 == 0) -- test whether two numbers are equal
 false          -- output
 print(1 ~= 0) -- test whether two numbers are not equal
 true          -- output
 print(true ~= false) -- is true not equal to false?
 true

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

 x = {}   -- creating an empty table
 print(x)
 table: 0x237f670  -- output

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:

 foo = function () print("hello") end -- declare the 
 function
 foo() -- call the function
 hello  -- Printed output
 print(foo) -- get the value of the variable "foo"
 function: 0035D6E8

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:

 x = function() print("hello") end
 x()
 hello
 print(x)
 function: 0035EA20

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:

 print(x)
 nil      --output as x is undefined
 x = 2.5  --x is assigned a value
 print(x)
 2.5     --value of x printed out

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.

a = 1   
b = "hello"
c = {}

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

a = 1
a = "hello"
a = {}

Querying type

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

 x = "123"  -- a string
 print(x, type(x)) -- show the value of x and its type string
 123     
 x = x + 7  -- add a number to the string which forces coercion
 print(x, type(x)) -- again show the value and type number
 130

Assignment statement

Setting the value of a variable is an assignment:

 x = 1   
 y = "hello"  
 print(x,y)
1       hello

Multiple assignment

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

 x, y = 2, "there"  --multiple assignment
 print(x,y)
 2       there   --output
 a,b,c,d,e,f = 1,"two",3,3.14159,"foo",{ this="a table" }
 print(a,b,c,d,e,f)
 1       two     3       3.14159 foo     table: 0035BED8

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.

 i = 7
 i, x = i+1, i  
 print(i, x)
 8       7

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:

 a,b = 1,2  -- set initial values
 print(a,b)
 1       2  -- output
 a,b = b,a  -- swap values around
 print(a,b)
 2       1  -- output
 a,b = b,a  -- and back again
 print(a,b)
1       2  -- output

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.

 a, a = 1, 2
 print(a)
  1       -- output

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.

 a,b,c = 1,2,3,4,5,6
 print(a,b,c)
 1       2       3

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

 a,b,c,d = 1,2
 print(a,b,c,d)
 1       2       nil     nil

Numbers manipulations

Lua supports only one type of number: floating-point numbers. By default, these are double-precision 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

= 1 + 2
3

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

= 543.21E8
54321000000

= 2.56e-4
0.000256

You can assign numbers to variables and do arithmetic:

 width = 7.5
 height = 12.7
 = width * height
 95.25

Number conversion

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

 = tonumber("123") + 25
 148

 x = tonumber("123.456e5")
 print(x)
12345600

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

 = (16 ^ 13) + 10 - (16 ^ 13)
 10.0

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.

 = 100 + "7"
 107  --output
 
 = "hello" + 234
stdin:1: attempt to perform arithmetic on a string value
stack traceback:
        stdin:1: in main chunk
        [C]: ?

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.

= 100 == "100"
false

 = 100 ~= "hello"
true

 = 100 == tonumber("100")
true

 = 100 <= "100"
stdin:1: attempt to compare number with string
stack traceback:
        stdin:1: in main chunk
        [C]: ?

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.

 = "hello"
 hello

 = 'hello'
 hello

 = [[hello]]
 hello

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

 = 'hello "Lua user"'
 hello "Lua user"  -- output

 = "Its [[content]] hasn't got a substring."
 Its [[content]] hasn't got a substring. -- output

Double bracketed strings also have a few other special properties.

Escape sequences

Lua can also handle C-like escape sequences.

= "hello \"Lua user\""
hello "Lua user"        -- output

= 'hello\nNew line\tTab'
hello                   
New line        Tab

Escape sequences are not recognized when using double brackets, so:

 = [[hello\nNew line\tTab]]

 hello\nNew line\tTab

Multiline quotes

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

= [[Multiple lines of text
>> can be enclosed in double square
>> brackets.]]

Multiple lines of text
can be enclosed in double square
brackets.

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.

 

 = [[one [[two]] one]]        -- bad
stdin:1: nesting of [[...]] is deprecated near '[' -- returns an error

= [=[one [[two]] one]=]      -- ok
one [[two]] one

= [===[one [[two]] one]===]  -- ok too
one [[two]] one

Concatenation

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

 who = "John"
 = "hello "..who
 hello John   -- output

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

= "Green bottles: "..10  -- concatenating a string and integer
Green bottles: 10   -- output

= type("Green bottles: "..10)  -- using the type function
string                         -- output

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.

 = "This is Lua version " .. 5.1 .. " we are using."
This is Lua version 5.1 we are using.

= "Pi = " .. math.pi
Pi = 3.1415926535898

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

= string.format("%.3f", 5.1)
5.100

= "Lua version " .. string.format("%.1f", 5.1)
Lua version 5.1

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.

 = string.byte("ABCDE", 2) -- return the ASCII value of the second character
66

 = string.char(65,66,67,68,69) -- return a string constructed from ASCII values
ABCDE

 = string.find("hello Lua user", "Lua") -- find substring "Lua"
7       9

 = string.find("hello Lua user", "l+") -- find one or more occurrences of "l"
3       4

 = string.format("%.7f", math.pi) -- format a number
3.1415927

 = string.format("%8s", "Lua") -- format a string
     Lua

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

 x = 7
 print(x)
 7   -- output
 = 7
 7 -- output

Arithemetic expressions

Lua has the usual binary arithmetic operators.

 

 = 2+3, 5-12, 2*7, 7/8
 5       -7      14      0.875  --output
  • Unary negation:
 = -(-10), -(10)
10      -10
  • Modulo (division remainder):
 = 15%7, -4%3, 5.5%1
 1       2       0.5

Control statement

Lua tables

Function definition in lua

Lua scope

Lua standard libraries