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
localkeyword. - 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.
-- 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 6Output:
5 nil
6 6
5 6Data 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 Type | Description |
|---|---|
| nil | Only value nil belongs to this class, represents an invalid value (equivalent to false in conditional expressions). |
| boolean | Contains two values: false and true. |
| number | Represents double-precision real floating-point numbers |
| string | Strings are represented by a pair of double or single quotes |
| function | Functions written in C or 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))) --> stringControl 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
--[ 0 is true ]
if(0)
then
print("0 is true")
endOutput:
0 is trueif...else Statement
if(boolean expression)
then
--[ Executes when boolean expression is true --]
else
--[ Executes when boolean expression is false --]
endExample to determine variable a's value:
--[ 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:
a is greater than 20
a's value is: 100if...elseif...else Statement
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 --]
endExample to determine variable a's value:
--[ 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:
No match for a's value
a's actual value is: 100Nested if
You can insert other if or elseif statements within an if or elseif statement. Syntax:
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--[ 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:
a's value is 100 b's value is 200
a's value is : 100
b's value is : 200Loop 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
for var=exp1,exp2,exp3 do
<loop body>
endvar 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.
for i=1,f(x) do
print(i)
end
for i=10,1,-1 do
print(i)
endThe 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:
function f(x)
print("function")
return x*2
end
for i=1,f(5) do print(i)
endOutput:
function
1
2
3
4
5
6
7
8
9
10Generic for Loop
The generic for loop traverses all values through an iterator function, similar to the foreach statement in Java.
-- Print all values of array a
a = {"one", "two", "three"}
for i, v in ipairs(a) do
print(i, v)
endi 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:
#!/usr/local/bin/lua
days = {"Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"}
for i,v in ipairs(days) do print(v) endOutput:
Sunday
Monday
Tuesday
Wednesday
Thursday
Friday
Saturdaywhile Loop
- The while loop statement repeatedly executes the loop body statements when the condition is true. Syntax:
while(condition)
do
statements
endWhen condition is false, it skips the current loop and starts executing the immediately following statements in the script. Example:
a=10
while( a < 20 )
do
print("a's value is:", a)
a = a+1
endOutput:
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: 19Functions
- 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:
- Complete specified tasks, in which case functions are used as call statements;
- Compute and return values, in which case functions are used as expressions in assignment statements.
Function Definition
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
localkeyword 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.
--[[ 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:
Maximum value is 10
Maximum value is 6Multiple 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)
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:
23 3Operators
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:
| Operator | Description | Example |
|---|---|---|
| + | Addition | A + B outputs 30 |
| - | Subtraction | A - B outputs -10 |
| * | Multiplication | A * B outputs 200 |
| / | Division | B / A outputs 2 |
| % | Modulus | B % A outputs 0 |
| ^ | Exponentiation | A^2 outputs 100 |
| - | Unary minus | -A outputs -10 |
| // | Floor division | 5//2 outputs 2 |
Relational Operators
Assume A has value 10, B has value 20:
| Operator | Description | Example |
|---|---|---|
| == | 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:
| Operator | Description | Example |
|---|---|---|
| and | Logical AND operator. Returns A if A is false, otherwise returns B | (A and B) is false |
| or | Logical OR operator. Returns A if A is true, otherwise returns B | (A or B) is true |
| not | Logical NOT operator. Inverts the logical result, returns false if condition is true | not(A and B) is true |
Other Operators
The following table lists concatenation operators and operators for calculating table or string length:
| Operator | Description | Example |
|---|---|---|
| .. | Concatenates two strings | a..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:
^
not - (unary)
* / %
+ -
..
< > <= >= ~= ==
and
orAll binary operators except ^ and .. are left-associative.
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:
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:
(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.0Strings
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
local str1 = 'This is a string.'
local str2 = "This is also a string."- A sequence of characters between double quotes
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 ]]
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:
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:
"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:
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 14Escape 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 Character | Meaning | ASCII Code (Decimal) |
|---|---|---|
| \a | Bell (BEL) | 007 |
| \b | Backspace (BS), moves current position to previous column | 008 |
| \f | Form feed (FF), moves current position to start of next page | 012 |
| \n | Line feed (LF), moves current position to start of next line | 010 |
| \r | Carriage return (CR), moves current position to start of current line | 013 |
| \t | Horizontal tab (HT) (jumps to next TAB position) | 009 |
| \v | Vertical tab (VT) | 011 |
| \ | Represents a backslash character '' | 092 |
| ' | Represents a single quote (apostrophe) character | 039 |
| " | Represents a double quote character | 034 |
| \0 | Null character (NULL) | 000 |
| \ddd | Any character represented by 1 to 3 octal digits | Three octal digits |
| \xhh | Any character represented by 1 to 2 hexadecimal digits | Two hexadecimal digits |
String Operations
Common string operations
| No. | Method & Purpose |
|---|---|
| 1 | string.upper(argument): Converts entire string to uppercase letters. |
| 2 | string.lower(argument): Converts entire string to lowercase letters. |
| 3 | string.sub(s, i [, j]): s is the string to substring, i is start position, j is end position, defaults to -1 (last character). |
| 4 | string.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 |
| 5 | string.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 |
| 6 | string.reverse(arg) Reverses string string.reverse("Lua")auL |
| 7 | string.format(...) Returns a formatted string similar to printf string.format("the value is:%d",4)the value is:4 |
| 8 | string.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)abcdstring.byte("ABCD",4)68string.byte("ABCD")65 |
| 9 | string.len(arg) Calculates string length string.len("abc")3 |
| 10 | string.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 |
| 12 | string.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) endHelloaivision |
| 13 | string.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 questionsstring.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:
- Sign: A + sign indicates that the following numeric escape will show positive sign for positive numbers. By default only negative numbers show sign.
- Placeholder: A 0, used as placeholder when string width is specified later. Default placeholder is space when not filled.
- Alignment identifier: When string width is specified, defaults to right alignment, adding - changes to left alignment.
- Width value
- 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.
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:
Basic formatting Hello Ai-Vision
Date formatting 02/01/2023
0.3333Other examples:
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 monString Substring
-- 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:
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
-- Create an array
local myArray = {10, 20, 30, 40, 50}
-- Access array elements
print(myArray[1]) -- Output 10
print(myArray[3]) -- Output 30To calculate the length of an array (number of elements in the array), use the # operator:
local myArray = {10, 20, 30, 40, 50}
-- Calculate array length
local length = #myArray
print(length) -- Output 5One-dimensional arrays can use for loop to iterate through array elements:
-- Create an array
local myArray = {10, 20, 30, 40, 50}
-- Loop through array
for i = 1, #myArray do
print(myArray[i])
endOutput:
10
20
30
40
50