• Guides
  • Scripting
  • Basic lua syntax

Lua

Lua is a lightweight,open-sourced,scripting language that is written in standard C language. It is designed to embed it in applications, so as to provide flexible extension and customization for applications.

Characteristics

  • Lightweight: Lua is written in standard C language and is open-sourced, which can be easily embedded in other programs.

  • Extensible: Lua has easy-to-use extensible interfaces and mechanisms which are provided by the host language (typically C or C++). Lua can use them just like built-in functions.

  • Other characteristics:

    • Lua supports procedure-oriented programming and functional programming.
    • Lua supports procedure-oriented programming and functional programming.
    • Lua supports automatic memory management. Lua only provides one general type of table which can be used to implement arrays, hash tables, sets, and objects.
    • Lua provides built-in pattern matching and closure. In Lua, a function can also be considered as a value. Lua supports multiple threads (collaborative processes instead of threads supported by the operating system).
    • Lua can easily support some key mechanisms required for object-oriented programming by closure and tables, such as data abstraction, virtual function, inheritance, and overloading.

Basic Syntax

Interactive Programming

Lua provides an interactive programming mode. You can code in the command line and immediately view the effect.

The Lua interactive programming mode can be enabled through the command lua -i or lua:

    $ lua -i 
    $ Lua 5.3.0  Copyright (C) 1994-2015 Lua.org, PUC-Rio
    >

In the command, type in the following command:

    > print("Hello World!")

Press Enter. The output result is as follows:

    > print("Hello World!")
    Hello World!
    >

Scripted Programming

You can save Lua program code to a file with .lua as the extension and execute it. This mode is called scripted programming. For example, you can store the following code in a script file named hello.lua:

    print("Hello World!")
    print("www.theclicli.com")

Execute the above script by lua command, the output result is:

    $ lua hello.lua
    Hello World!
    www.theclicli.com

We can also add #!/usr/local/bin/lua at the beginning of the script file to execute the script.

    #!/usr/local/bin/lua
 
    print("Hello World!")
    print("www.TheCLICLI.com")

In the above code, you specify the Lua interpreter /usr/local/bin directory. If you want the interpreter ignores a line of the statement, you can add # at the beginning of the line. Next, you need to add executable permission for the script and execute the following commands:

    ./hello.lua 
 
    Hello World!
    www.theclicli.com

Data Type

Lua is a dynamic language. There is no need to define variable types and only need to assign values to variables. A value can be stored in a variable and passed as a parameter or returned as a result.

Lua supports eight basic data types, namely nil, boolean, number, string, userdata, function, thread, and table.

⚠️

Note: You can use the type function to test the type of a given variable or value.

Data TypeBrief Introduction
nilNull value. In this type, only the nil value exists. It equals false in a conditional expression.
booleanThe value can be true or false.
numberIt indicates a real floating point number of double precision.
stringIt is indicated by a pair of double or single quotation marks.
userdataIt indicates any C data structure stored in a variable.
functionIt indicates a function, which is written by C or Lua.
threadIt indicates an independent route for execution and is used to execute a coroutine.
tableA table in Lua is an "associative array" whose index may be a number, string, or table type. In Lua, a table is created by "construction expression". The simplest construction expression is , which is used to create an empty table.

Variable

Before using a variable, you need to declare it in the code, that is, create the variable.

Before executing the code, the compiler needs to know how to create a storage area for the statement variable to store its value.

Lua supports three types of variables: global variables, local variables, and fields in the table. Variables in Lua are global variables by default, no matter whether they are variables in a statement block or variables in a function, unless explicitly declared as local variables using local.

The scope of a local variable is from the declaration location to the end of the statement block where the local variable is stored.

The default value of a variable is nil.

= 1               -- global variable
    local b = 1        -- local variable
 
    function joke()
        c = 1           -- global variable
        local d = 2     -- local variable
    end
 
    joke()
    print(c,d)          --> 1 nil
 
    do
        local a = 3     -- local variable
        b = 3           -- Reassign a value to a local variable
        print(a,b);     --> 3 3
    end
 
    print(a,b)      --> 1 3

Assignment Statement

Assignment is the most basic method to change the value of a variable and to change fields in a table.

Lua can assign values to multiple variables at the same time. Elements in the variable list and value list are separated using commas. The values on the right of an assignment statement are sequentially assigned to the variables on the left.

When encountering an assignment statement, Lua first calculates all the values on the right and then performs assignment. Therefore, you can exchange the values of variables in this way:

    A, B =B, A                     -- swap 'a' for 'b'
    a[i], a[j] = a[j], a[i]         -- swap 'a[i]' for 'a[j]'

When the number of variables differs from the number of values, Lua always adopts the following policy based on the number of variables:

  1. When the number of variables is greater than the number of values, Lua complements nil based on the number of variables.

  2. When the number of variables is smaller than the number of values, excessive values are ignored.

Multi-value assignment is often used to exchange variables or return function calls to variables:

    a, b = f()
⚠️

Note: Local variables should be used as much as possible, which brings the following benefits:

  1. Naming conflicts are avoided.
  2. Accessing local variables is faster than accessing global variables.

Index

Square brackets [] are used to index a table.

    t[i]
    t.i               //A simplified writing method when the type of index is string
    gettable_event(t,i)  //The essence of the index is a function call.

Loop

In many cases, you have to perform some regular repeated operations. Therefore, some statements need to be repeatedly executed in a program.

A group of statements that are repeatedly executed is called a loop. Whether the loop can be continuously repeated depends on the termination condition of the loop.

A loop statement consists of two parts: loop and loop termination condition.

Lua provides the following loop processing methods:

Loop TypeDescription
while loopBefore executing a loop, Lua checks whether the condition is true. When the condition is true, the loop is executed repeatedly.
for loopThe loop is repeatedly executed. The number of repeated executions can be controlled in the for statement.
repeat…untilThe loop is repeated until the specified condition is true.
Loop nestingOne or more loop statements can be embedded in a loop (while do...end; for...do...end; repeat... until).

Loop Control Statement

The loop control statement is used to control the flow of a program to achieve various structural modes of the program.

Lua supports the following loop control statements:

Control StatementDescription
break statementExit the current loop or statement and start to execute the following statement.
goto statementTransfer the control point of the program to a label.

Flow Control

The flow control statements of Lua are set through one or more conditional statements. When the condition is true, the specified code is executed; when the condition is false, another specified code is executed.

The result of the conditional expression for controlling the structure can be any value. Lua considers false and nil to be false, and considers true and non-nil to be true.

⚠️

Note: Zero is true in Lua.

For example, execute the following statements.

    IF (0)
    then
        print("TRUE")
    end

The output result is: TRUE

Lua provides the following control structure statements:

StatementDescription
if statementAn if statement uses a Boolean expression as the condition, followed by other statements.
if…else statementExecute the else statement when the conditional expression of the if statement is false.
if nestingYou can use one or more if or else if statements in if or else if statements.

Functions in Lua

In Lua, functions are the main method for abstracting statements and expressions. Functions can be used to handle some special tasks or calculate some values.

Lua provides many built-in functions that can be easily called in a program. For example, the print() function can print input parameters on the console.

Functions in Lua are used to:

  • Complete the specified task. In this case, the function is used as a call statement.

  • Calculate and return a value. In this case, the function is used as an expression for an assignment statement.

Function Definition

The function definition format of Lua is as follows:

    optional_function_scope function function_name(argument1,argument2, argument3..., argument_n)
        function_body
        return result_params_comma_separated
    end
  • optional_function_scope: This parameter determines whether the specified function is a global or local function. If this parameter is not set, the function is a global function by default. To set a function to a local function, use the keyword local.

  • function_name: Specifies the function name.

  • argument1, argument2, argument3..., argument_n: Parameters of the function. Multiple parameters are separated by commas. Functions can have no parameters.

  • function_body: Function body, a block of code statements that need to be executed in a function.

  • result_params_comma_separated: Values returned by the function. Functions in Lua can return multiple values, which are separated using commas.

There is an example of a function, which returns the minimum of two values.

    function min(num1, num2)
 
    if (num1< num2) then
        result = num1;
    else
        result = num2;
    end
 
    return result;
    end
    -- Call a function
 
    print("The minimum value of two values is: ",MIN(2,6))

The output result is:

    The minimum value of two values is: 2.

In Lua, you can pass a function as a parameter to another function, for example:

    myprint = function(param)
    print("Print parameter here -   <<",param,">>")
    end
 
    function add(num1,num2,functionPrint)
    result = num1 + num2
    -- Passed function parameter
    functionPrint(result)
    end
    myprint(8)
    -- The myprint function is passed as a parameter.
    add(4,5,myprint)

The output result is:

    This is a print function - << 8 >>
    This is a print function - << 9 >>

Returned Values

A function in Lua can return multiple result values. For example, the function string.find returns the "start and end subscripts" of the matching string (or it returns nil if no matching string exists).

    > s, e = string.find("www.theclicli.com", "clicli") 
    > print(s, e)
    8   12

Variable Parameter

A function in Lua can accept a variable number of parameters. Similar to C language, Lua uses three dots in the function parameter list to indicate that the function has variable parameters.

    function add(...)  
    local s = 0  
    for i, v  in  ipairs{...} do   --> {...} indicates an array consisting of all variable parameters.  
        s = s + v  
    end  
    return s  
    end  
    print(add(3,4,5,6,7))  --->25

Operators in Lua

An operator is a special symbol that tells the interpreter to perform a specific mathematical or logical operation. Lua provides the following operators:

Arithmetic operators

The following table lists commonly used arithmetic operators in Lua (A is set to 10 and B is set to 20):

OperatorDescriptionExample
+AddThe output result of A + B is 30.
-SubtractThe output result of A - B is -10.
*MultiplyThe output result of A * B is 200.
/DivideThe output result of B/A is 2.
%RemainderThe output result of B % A is 0.
^PowerThe output result of A^2 is 100.
-MinusThe output result of -A is -10.

Relational operators

The following table lists commonly used relational operators in Lua (A is set to 10 and B is set to 20):

OperatorDescriptionExample
==Equal to. Two values are checked to determine whether they are equal. If they are equal, true is returned. Otherwise, false is returned.The output result of (A == B) is false.
~=Not equal to. Two values are checked to determine whether they are equal. If they are equal, false is returned. Otherwise, true is returned.The output result of (A ~= B) is true.
>Greater than. If the value on the left is greater than the value on the right, true is returned. Otherwise, false is returned.The output result of (A > B) is false.
<Smaller than. If the value on the left is greater than the value on the right, false is returned. Otherwise, true is returned.The output result of (A < B) is true.
>=Greater than or equal to. If the value on the left is greater than or equal to the value on the right, true is returned. Otherwise, false is returned.The output result of (A >= B) is false.
<=Smaller than or equal to. If the value on the left is smaller than or equal to the value on the right, true is returned. Otherwise, false is returned.The output result of (A <= B) is true.

Logical operators

The following table lists commonly used logical operators in Lua (A is set to true and B is set to false):

OperatorDescriptionExample
andLogical AND operator. If A is false, A is returned. Otherwise, B is returned.The output result of (A and B) is false.
orLogical OR operator. If A is true, A is returned. Otherwise, B is returned.The output result of (A or B) is true.
notLogical NOT operator. It is contrary to the result of a logical operation. If the condition is true, logical NOT is false.The output result of not(A and B) is true.

Other operators

The following table lists concatenation operators and operators for calculating the length of a table or string in Lua:

OperatorDescriptionExample
..Operator for connecting two stringsa..b. When a is "Hello" and b is "Clicli", the output result is "Hello Clicli".
#Unary operator. The length of a string or table is returned.For #"Hello", 5 is returned.

Example:

    -- Distance between two points
    function distance(p1, p2)
        -- Data correction
        local x1 = p1.x or 0
        local y1 = p1.y or 0
        local z1 = p1.z or 0
        
        local x2 = p2.x or 0
        local y2 = p2.y or 0
        local z2 = p2.z or 0
        
        -- c^2 = a^2 + b^2
        return math.abs(math.sqrt((x2 - x1)^2 + (y2 - y1)^2 + (z2 - z1)^2))
    end
 
    local p1, p2 = {
        x = 1,
        y = 2,
        z = 3
    }, {
        x = 3,
        y = 2,
        z = 1
    }
    print(distance(p1, p2)) -- answer:2.8284271247462