A brief introduction to Lua

1 Basics of Lua

The Lua scripting language was originally designed for extending the functionality of existing applications, but it is often used as a standalone language. It is very similar to Pascal.

The language has the objectives of simplicity, efficiency and portability of code. The full Lua language documentation can be found at http://www.lua.org/manual/5.1/ . Below are some basic elements that you need to get started with writing scripts in Lua.

1.1 STRUCTURE OF THE CODE

In Lua, commands are typed, as in other programming languages ​​in lines one under the other.  There is no need for a termination character at the end of each line (however Lua ignores a semicolon at the end of the line, so you do not have to get rid of habits acquired from other programming languages which ​​require that symbol).

1.2 DECLARING LOCAL VARIABLES

If you want to declare a local variable, type:

Alternatively, we can assign an initial value when we declare teh variable:

For example:

1.3 CONDITIONAL STATEMENTS

Conditional statements have the form:

For example:

This example means:

“If the variable a has a value of 1, then assign the value 2 to the variable b and the value 3 to the variable c,
otherwise, if the variable a has a value of 2, then assign the value 3 to variable b and the value 4 to the variable c,
otherwise assign the value of 4 to variable b and the value of 5 to the variable c

1.3 OPERATORS

Comparison operators:

== equal
~ = different (not equal)
> greater than
< less than
> = greater than or equal
<= Less than or equal

Arithmetic operators:

+ addition
subtraction
* multiplication
/ division
% the remainder (modulo)

Logical operators:

and conjunction
or alternative
not negation

The concatenation operator:

To combining strings (text variables) in Lua, we use two dots “..”

For example:

1.4 Types of variables (number vs string)
Lua does not explicitly declare the type of a variable (as is the case, for example, in C / C++).

The type is dynamically determined based on the value that is assigned to the variable:

stringVariable will create a variable of type string and numberVariable will create a variable of type number.

The coercion mechanism in Lua provides automatic type conversion if possible. This means that if you give the variable stringVariable to a function which expects a number (not text), it will be automatically converted.

However, problems may arise when comparing variables of type number with variables of type string. In such cases, you should explicitly convert the string to a number value using the tonumber function:

The code on lines 1-5 will generate the following error:

(line 2): attempt to compare number with string