Skip to content

Basic Syntax

Variable Definition

  • Variables must be declared in code before use, meaning the variable must be created.
  • Before executing code, the compiler needs to know how to allocate storage for statement variables to store variable values.
  • Lua has three types of variables: global variables, local variables, and fields in tables.
  • All variables in Lua are global by default, even within statement blocks or functions, unless explicitly declared as local using the local keyword.
  • The scope of a local variable extends from the point of declaration to the end of the statement block.
  • The default value for variables is nil.
lua
-- test.lua script
a = 5               -- Global variable
local b = 5         -- Local variable

function joke()
    c = 5           -- Global variable
    local d = 6     -- Local variable
end

joke()
print(c,d)          --> 5 nil

do 
    local a = 6     -- Local variable
    b = 6           -- Reassign local variable
    print(a,b);     --> 6 6
end

print(a,b)      --> 5 6

Output:

lua
5    nil
6    6
5    6

Data Types

  • Lua is a dynamically typed language, variables don't need type definitions, just assign values to variables.
  • Values can be stored in variables, passed as parameters, or returned as results.
  • Lua has 8 basic types, AIV uses only 5 of them: nil, boolean, number, string, function.
Data TypeDescription
nilOnly value nil belongs to this class, represents an invalid value (equivalent to false in conditional expressions).
booleanContains two values: false and true.
numberRepresents double-precision real floating-point numbers
stringStrings are represented by a pair of double or single quotes
functionFunctions written in C or Lua
lua
print(type("Hello world"))      --> string
print(type(10.4*3))             --> number
print(type(print))              --> function
print(type(type))               --> function
print(type(true))               --> boolean
print(type(nil))                --> nil
print(type(type(X)))            --> string

Control Flow

  • Lua programming language control flow statements set one or more conditional statements. Executes specified program code when condition is true, and other specified code when condition is false.

if Statement

lua
--[ 0 is true ]
if(0)
then
    print("0 is true")
end

Output:

lua
0 is true

if...else Statement

lua
if(boolean expression)
then
   --[ Executes when boolean expression is true --]
else
   --[ Executes when boolean expression is false --]
end

Example to determine variable a's value:

lua
--[ Define variable --]
a = 100;
--[ Check condition --]
if( a < 20 )
then
   --[ Executes when if condition is true --]
   print("a is less than 20" )
else
   --[ Executes when if condition is false --]
   print("a is greater than 20" )
end
print("a's value is:", a)

Output:

lua
a is greater than 20
a's value is:    100

if...elseif...else Statement

lua
if( boolean expression 1)
then
   --[ Executes when boolean expression 1 is true --]

elseif( boolean expression 2)
then
   --[ Executes when boolean expression 2 is true --]

elseif( boolean expression 3)
then
   --[ Executes when boolean expression 3 is true --]
else 
   --[ Executes when none of the above boolean expressions are true --]
end

Example to determine variable a's value:

lua
--[ Define variable --]
a = 100

--[ Check boolean condition --]
if( a == 10 )
then
   --[ Print if condition is true --]
   print("a's value is 10" )
elseif( a == 20 )
then   
   --[ Print if else if condition is true --]
   print("a's value is 20" )
elseif( a == 30 )
then
   --[ Print if else if condition is true --]
   print("a's value is 30" )
else
   --[ Print when none of the conditions are true --]
   print("No match for a's value" )
end
print("a's actual value is: ", a )

Output:

lua
No match for a's value
a's actual value is:     100

Nested if

You can insert other if or elseif statements within an if or elseif statement. Syntax:

lua
if( boolean expression 1)
then
   --[ Executes when boolean expression 1 is true --]
   if(boolean expression 2)
   then
      --[ Executes when boolean expression 2 is true --]
   end
end
lua
--[ Define variables --]
a = 100;
b = 200;

--[ Check condition --]
if( a == 100 )
then
   --[ Execute following if condition check when if condition is true --]
   if( b == 200 )
   then
      --[ Executes when if condition is true --]
      print("a's value is 100 b's value is 200" );
   end
end
print("a's value is :", a );
print("b's value is :", b );

Output:

lua
a's value is 100 b's value is 200
a's value is :    100
b's value is :    200

Loop Control

for Loop

  • The for loop statement can repeatedly execute specified statements, with repetition count controlled in the for statement.
  • There are two main types of for statements: numeric for loop, generic for loop

Numeric for Loop

lua
for var=exp1,exp2,exp3 do  
    <loop body>  
end

var changes from exp1 to exp2, incrementing var by exp3 each time, and executes the "loop body" once. exp3 is optional, defaults to 1 if not specified.

lua
for i=1,f(x) do
    print(i)
end
 
for i=10,1,-1 do
    print(i)
end

The three expressions in for are evaluated once before the loop starts and not evaluated again later. For example, f(x) above will only be executed once before the loop starts, and its result is used in subsequent loops. Example:

lua
function f(x)  
    print("function")  
    return x*2   
end  
for i=1,f(5) do print(i)  
end

Output:

lua
function
1
2
3
4
5
6
7
8
9
10

Generic for Loop

The generic for loop traverses all values through an iterator function, similar to the foreach statement in Java.

lua
-- Print all values of array a  
a = {"one", "two", "three"}
for i, v in ipairs(a) do
    print(i, v)
end

i is the array index value, v is the array element value at the corresponding index. ipairs is an iterator function provided by Lua to iterate arrays. Example:

lua
#!/usr/local/bin/lua  
days = {"Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"}  
for i,v in ipairs(days) do  print(v) end

Output:

lua
Sunday
Monday
Tuesday
Wednesday
Thursday
Friday
Saturday

while Loop

  • The while loop statement repeatedly executes the loop body statements when the condition is true. Syntax:
lua
while(condition)
do
   statements
end

When condition is false, it skips the current loop and starts executing the immediately following statements in the script. Example:

lua
a=10
while( a < 20 )
do
   print("a's value is:", a)
   a = a+1
end

Output:

lua
a's value is:    10
a's value is:    11
a's value is:    12
a's value is:    13
a's value is:    14
a's value is:    15
a's value is:    16
a's value is:    17
a's value is:    18
a's value is:    19

Functions

  • Functions are the main method for abstracting statements and expressions. They can be used to handle special tasks or compute values.
  • Functions have two main purposes:
  1. Complete specified tasks, in which case functions are used as call statements;
  2. Compute and return values, in which case functions are used as expressions in assignment statements.

Function Definition

lua
optional_function_scope function function_name( argument1, argument2, argument3..., argumentn)
    function_body
    return result_params_comma_separated
end
  • optional_function_scope: This parameter is optional and specifies whether the function is global or local. If not set, defaults to global function. Use the local keyword to set function as local.
  • function_name: Specifies the function name.
  • argument1, argument2, argument3..., argumentn: Function parameters, multiple parameters separated by commas. Functions can also have no parameters.
  • function_body: Function body, the code statement block to be executed in the function.
  • result_params_comma_separated: Function return values. Lua functions can return multiple values, each value separated by commas.
lua
--[[ Function returns maximum of two values --]]
function max(num1, num2)

   if (num1 > num2) then
      result = num1;
   else
      result = num2;
   end

   return result; 
end
-- Call function
print("Maximum value is ",max(10,4))
print("Maximum value is ",max(5,6))

The above example defines function max() with parameters num1, num2, used to compare two values and return the maximum. Output:

lua
Maximum value is     10
Maximum value is     6

Multiple Return Values

  • Functions can return multiple result values, like string.find, which returns the "start and end indices" of the matched string (returns nil if no match exists)
lua
function maximum (a)
    local mi = 1             -- Maximum value index
    local m = a[mi]          -- Maximum value
    for i,val in ipairs(a) do
       if val > m then
           mi = i
           m = val
       end
    end
    return m, mi
end

print(maximum({8,10,23,12,5}))

The above example shows that multiple values can be returned by listing them after return. Output:

lua
23    3

Operators

Operators are special symbols used to tell the interpreter to perform specific mathematical or logical operations. Lua provides the following operator types:

  • Arithmetic operators
  • Relational operators
  • Logical operators
  • Other operators

Arithmetic Operators

Assume A has value 10, B has value 20:

OperatorDescriptionExample
+AdditionA + B outputs 30
-SubtractionA - B outputs -10
*MultiplicationA * B outputs 200
/DivisionB / A outputs 2
%ModulusB % A outputs 0
^ExponentiationA^2 outputs 100
-Unary minus-A outputs -10
//Floor division5//2 outputs 2

Relational Operators

Assume A has value 10, B has value 20:

OperatorDescriptionExample
==Equality, tests if two values are equal, returns true if equal, otherwise false(A == B) is false
~=Inequality, tests if two values are equal, returns true if not equal, otherwise false(A ~= B) is true
>Greater than, returns true if left value is greater than right value, otherwise false(A > B) is false
<Less than, returns true if left value is less than right value, otherwise false(A < B) is true
>=Greater than or equal, returns true if left value is greater than or equal to right value, otherwise false(A >= B) returns false
<=Less than or equal, returns true if left value is less than or equal to right value, otherwise false(A <= B) returns false

Logical Operators

Assume A has value true, B has value false:

OperatorDescriptionExample
andLogical AND operator. Returns A if A is false, otherwise returns B(A and B) is false
orLogical OR operator. Returns A if A is true, otherwise returns B(A or B) is true
notLogical NOT operator. Inverts the logical result, returns false if condition is truenot(A and B) is true

Other Operators

The following table lists concatenation operators and operators for calculating table or string length:

OperatorDescriptionExample
..Concatenates two stringsa..b, where a is "Hello ", b is "AI-Vision", outputs "Hello AI-Vision"
#Gets string length#"Hello" returns 5

Operator Precedence

From highest to lowest:

lua
^
not    - (unary)
*      /       %
+      -
..
<      >      <=     >=     ~=     ==
and
or

All binary operators except ^ and .. are left-associative.

lua
a+i < b/2+1          <-->       (a+i) < ((b/2)+1)
5+x^2*8              <-->       5+((x^2)*8)
a < y and y <= z     <-->       (a < y) and (y <= z)
-x^2                 <-->       -(x^2)
x^y^z                <-->       x^(y^z)

Example:

lua
a = 20
b = 10
c = 15
d = 5

e = (a + b) * c / d;-- ( 30 * 15 ) / 5
print("(a + b) * c / d operation value  :",e )

e = ((a + b) * c) / d; -- (30 * 15 ) / 5
print("((a + b) * c) / d operation value :",e )

e = (a + b) * (c / d);-- (30) * (15/5)
print("(a + b) * (c / d) operation value :",e )

e = a + (b * c) / d;  -- 20 + (150/5)
print("a + (b * c) / d operation value   :",e )

Output:

lua
(a + b) * c / d operation value  :    90.0
((a + b) * c) / d operation value :    90.0
(a + b) * (c / d) operation value :    90.0
a + (b * c) / d operation value   :    50.0

Strings

A string is a sequence of characters composed of numbers, letters, and underscores.
String is a basic data type used to store text data.
Strings can contain any characters, including letters, numbers, symbols, spaces, and other special characters.
Strings can be represented in three ways:

  • A sequence of characters between single quotes
lua
local str1 = 'This is a string.'
local str2 = "This is also a string."
  • A sequence of characters between double quotes
lua
local str = "Hello, "
str = str .. "World!"  -- Create a new string and assign it to str
print(str)  -- Output "Hello, World!"
  • A sequence of characters between [[ and ]]
lua
local multilineString = [[
This is a multiline string.
It can contain multiple lines of text.
No need for escape characters.
]]

print(multilineString)

Examples of the three string representation methods:

lua
string1 = "Hello"
print("\"String 1 is\"",string1)
string2 = 'AI-Vision'
print("String 2 is",string2)

string3 = [["Hello AI-Vision"]]
print("String 3 is",string3)

Output:

lua
"String 1 is"    Hello
String 2 is    AI-Vision
String 3 is    "Hello AI-Vision"

String Length Calculation

To calculate the length of a string (number of characters), use the string.len function or utf8.len function. For strings containing Chinese characters, generally use utf8.len. The string.len function is used to calculate the length of strings containing only ASCII characters. Example:

lua
local myString = "Hello, 世界!"

-- Calculate string length (character count)
local length1 = utf8.len(myString)
print(length1) -- Output 9

-- string.len function will cause inaccurate results
local length2 = string.len(myString)
print(length2) -- Output 14

Escape Characters

Escape characters are used to represent characters that cannot be displayed directly, such as backspace, carriage return, etc. For example, use " to represent double quotes within strings.
All escape characters and their meanings:

Escape CharacterMeaningASCII Code (Decimal)
\aBell (BEL)007
\bBackspace (BS), moves current position to previous column008
\fForm feed (FF), moves current position to start of next page012
\nLine feed (LF), moves current position to start of next line010
\rCarriage return (CR), moves current position to start of current line013
\tHorizontal tab (HT) (jumps to next TAB position)009
\vVertical tab (VT)011
\Represents a backslash character ''092
'Represents a single quote (apostrophe) character039
"Represents a double quote character034
\0Null character (NULL)000
\dddAny character represented by 1 to 3 octal digitsThree octal digits
\xhhAny character represented by 1 to 2 hexadecimal digitsTwo hexadecimal digits

String Operations

Common string operations

No.Method & Purpose
1string.upper(argument):
Converts entire string to uppercase letters.
2string.lower(argument):
Converts entire string to lowercase letters.
3string.sub(s, i [, j]):
s is the string to substring, i is start position, j is end position, defaults to -1 (last character).
4string.gsub(mainString,findString,replaceString,num)
Replaces in string.
mainString is the string to operate on, findString is the character to replace, replaceString is the replacement character, num is replacement count (can be omitted, then replaces all), e.g.:
string.gsub("aaaa","a","z",3);
zzza 3
5string.find (str, substr, [init, [plain]])
Searches for specified content substr in target string str. If a matching substring is found, returns start and end indices, otherwise returns nil.
init specifies search start position, defaults to 1, can be negative indicating character count from end.
plain indicates whether to use simple mode, defaults to false, true only does simple substring search, false uses regex pattern matching.
Example finding start and end indices of "Lua":
string.find("Hello Lua user", "Lua", 1)
7 9
6string.reverse(arg)
Reverses string
string.reverse("Lua")
auL
7string.format(...)
Returns a formatted string similar to printf
string.format("the value is:%d",4)
the value is:4
8string.char(arg) and string.byte(arg[,int])
char converts integer numbers to characters and concatenates, byte converts characters to integer values (can specify a character, defaults to first character)
string.char(97,98,99,100)
abcd
string.byte("ABCD",4)
68
string.byte("ABCD")
65
9string.len(arg)
Calculates string length
string.len("abc")
3
10string.rep(string, n)
Returns n copies of string
string.rep("abcd",2)
abcdabcd
11..
Concatenates two strings
print("www.ai-v".."ision.com")
www.ai-vision.com
12string.gmatch(str, pattern)
Returns an iterator function. Each call to this function returns the next substring in str that matches pattern. If no string matching pattern is found, returns nil
for word in string.gmatch("Hello ai vision", "%a+") do print(word) end
Hello
ai
vision
13string.match(str, pattern, init)
string.match() only finds the first match in source string str. Parameter init is optional, specifies search start point, defaults to 1.
On successful match, returns all capture results of the matching expression; if no capture markers set, returns the entire matched string. Returns nil when no successful match.
string.match("I have 2 questions for you.", "%d+ %a+")
2 questions
string.format("%d, %q", string.match("I have 2 questions for you.", "(%d+) (%a+)"))
2, "questions"

String Formatting

The string.format() function generates strings with specific formats. The first parameter is the format, followed by various data corresponding to each symbol in the format.
Format strings make long strings much more readable. This function's format is very similar to printf() in C.
The following example demonstrates how to format strings:
Format strings may contain the following escape codes:

  • %c - Accepts a number and converts it to the corresponding character in ASCII table
  • %d, %i - Accepts a number and converts it to signed integer format
  • %o - Accepts a number and converts it to octal format
  • %u - Accepts a number and converts it to unsigned integer format
  • %x - Accepts a number and converts it to hexadecimal format, using lowercase letters
  • %X - Accepts a number and converts it to hexadecimal format, using uppercase letters
  • %e - Accepts a number and converts it to scientific notation format, using lowercase e
  • %E - Accepts a number and converts it to scientific notation format, using uppercase E
  • %f - Accepts a number and converts it to floating-point format
  • %g(%G) - Accepts a number and converts it to the shorter of %e(%E, corresponding %G) and %f formats
  • %q - Accepts a string and converts it to a format that can be safely read by Lua compiler
  • %s - Accepts a string and formats it according to given parameters

To further refine the format, parameters can be added after the % sign. Parameters are read in the following order:

  1. Sign: A + sign indicates that the following numeric escape will show positive sign for positive numbers. By default only negative numbers show sign.
  2. Placeholder: A 0, used as placeholder when string width is specified later. Default placeholder is space when not filled.
  3. Alignment identifier: When string width is specified, defaults to right alignment, adding - changes to left alignment.
  4. Width value
  5. Decimal places/String trimming: Decimal part n added after width value. If followed by f (floating-point escape, e.g., %6.3f) sets the floating-point number to keep only n decimal places. If followed by s (string escape, e.g., %5.3s) sets the string to display only first n characters.
lua
string1 = "Hello"
string2 = "Ai-Vision"
number1 = 10
number2 = 20
-- Basic string formatting
print(string.format("Basic formatting %s %s",string1,string2))
-- Date formatting
date = 2; month = 1; year = 2023
print(string.format("Date formatting %02d/%02d/%03d", date, month, year))
-- Decimal formatting
print(string.format("%.4f",1/3))

Output:

lua
Basic formatting Hello Ai-Vision
Date formatting 02/01/2023
0.3333

Other examples:

lua
string.format("%c", 83)                 -- Output S
string.format("%+d", 17.0)              -- Output +17
string.format("%05d", 17)               -- Output 00017
string.format("%o", 17)                 -- Output 21
string.format("%u", 3.14)               -- Output 3
string.format("%x", 13)                 -- Output d
string.format("%X", 13)                 -- Output D
string.format("%e", 1000)               -- Output 1.000000e+03
string.format("%E", 1000)               -- Output 1.000000E+03
string.format("%6.3f", 13)              -- Output 13.000
string.format("%q", "One\nTwo")         -- Output "One\
                                        --     Two"
string.format("%s", "monkey")           -- Output monkey
string.format("%10s", "monkey")         -- Output     monkey
string.format("%5.3s", "monkey")        -- Output   mon

String Substring

lua
-- String
local sourcestr = "prefix--abcdefgh--suffix"
print("\nOriginal string", string.format("%q", sourcestr))

-- Substring, 4th to 15th
local first_sub = string.sub(sourcestr, 4, 15)
print("\nFirst substring", string.format("%q", first_sub))

-- Get string prefix, 1st to 8th
local second_sub = string.sub(sourcestr, 1, 8)
print("\nSecond substring", string.format("%q", second_sub))

-- Get last 10 characters
local third_sub = string.sub(sourcestr, -10)
print("\nThird substring", string.format("%q", third_sub))

-- Index out of bounds, outputs original string
local fourth_sub = string.sub(sourcestr, -100)
print("\nFourth substring", string.format("%q", fourth_sub))

Output:

lua
Original string    "prefix--abcdefgh--suffix"

First substring    "fix--abcdefg"

Second substring    "prefix--"

Third substring    "gh--suffix"

Fourth substring    "prefix--abcdefgh--suffix"

Arrays

An array is a collection of elements of the same data type arranged in a certain order, which can be one-dimensional or multi-dimensional arrays.
In Lua, arrays are not a specific data type, but a data structure used to store a set of values.
Actually, Lua doesn't have a dedicated array type, but uses a data structure called "table" to implement array functionality.

One-dimensional Array

One-dimensional arrays are the simplest arrays, with linear list as their logical structure.
Access array elements using indices

lua
-- Create an array
local myArray = {10, 20, 30, 40, 50}

-- Access array elements
print(myArray[1])  -- Output 10
print(myArray[3])  -- Output 30

To calculate the length of an array (number of elements in the array), use the # operator:

lua
local myArray = {10, 20, 30, 40, 50}

-- Calculate array length
local length = #myArray

print(length) -- Output 5

One-dimensional arrays can use for loop to iterate through array elements:

lua
-- Create an array
local myArray = {10, 20, 30, 40, 50}

-- Loop through array
for i = 1, #myArray do
    print(myArray[i])
end

Output:

lua
10
20
30
40
50

AI-Vision, Making 3D Measurement Easier