Basic
Example
In the examples below, the content after the two dashes (--
) represents a single-line comment.
Example 1: Local vs. Global Variable Scope
This example illustrates the difference between local variables and script-level variables in terms of scope.
function func() -- Define a function that prints a and b when run
local a = 1 -- Local variable
b = 2 -- Script-level variable
print(a)
print(b)
end
func() -- Execute the function, printing values of a and b as 1 and 2
print(a) -- nil (Accessing outside of the variable scope, prints nil)
print(b) -- 2
Example 2: Local Variables Can Shadow Global Variables
This example shows that local variables can share names with global variables, but only the local variable is effective within the function. The blocks of code defined by do/end
, as well as loops and conditionals, also fall under this rule.
a = "a"
for i=10,1,-1 do
do
local a = 6 -- Local variable
print(a) -- 6 (The local variable a is used here)
end
end
print(a) -- a (The global variable a is used here)
Example 3: Global Variables and Their Behavior
This example highlights the difference between global variables and the two other variable scopes, as well as the persistent nature of global variables.
-- src0.lua in Project 1
-- Assume two global variables g1 and g2 have been added
-- g1 is non-persistent and has a value of 10
-- g2 is persistent and has a value of 20
local a = 1
b = 2
print(a) -- 1
print(b) -- 2
print(g1) -- 10
print(g2) -- 20
SetGlobalVariable("g1", 11) -- Assign value to the non-persistent global variable
SetGlobalVariable("g2", 22) -- Assign value to the persistent global variable
print(g1) -- 11
print(g2) -- 22
-- src0.lua in Project 2
-- Project 2 runs after Project 1
print(a) -- nil
print(b) -- nil
print(g1) -- 10 (The non-persistent variable returns to its original value)
print(g2) -- 22 (The persistent variable reflects the modification from Project 1)
Variable names can be any string made up of letters, underscores, and digits, provided they do not begin with a digit and do not include reserved keywords in Lua.
In Lua, variables do not require type definitions. You simply assign a value, and Lua will automatically determine the variable's type. You can change a variable's type by assigning it a value of a different type. However, variables defined in the "Monitoring > Global Variables" page must retain their original types; otherwise, an error will occur when the script runs.
Lua supports multiple data types, including numbers (number), booleans (boolean), strings (string), and tables (table). Arrays in Lua are a type of table.
Another special data type in Lua is nil
, which represents an empty value (no valid value). For example, printing a variable that has not been assigned a value will output nil
.
Numbers
In Lua, the number
type is a double-precision floating-point number and supports various operations. The following representations are all considered number
:
- 2
- 2.2
- 0.2
- 2e+1
- 0.2e-1
- 7.8263692594256e-06
Booleans
The boolean
type has only two possible values: true
(true) and false
(false). Lua treats false
and nil
as false; everything else is considered true, including the number 0
.
Strings
A string
is a sequence of characters composed of letters, numbers, and underscores. Strings can be represented in three ways:
- A sequence of characters enclosed in single quotes.
- A sequence of characters enclosed in double quotes.
- A sequence of characters enclosed in double square brackets (
[[
and]]
).
When performing arithmetic operations on a numeric string, Lua attempts to convert the string to a number.
Lua provides many methods to support string operations:
Method | Description |
---|---|
string.upper(argument) | Converts the entire string to uppercase. |
string.lower(argument) | Converts the entire string to lowercase. |
string.gsub(mainString, findString, replaceString, num) | Replaces occurrences of findString with replaceString in mainString ; num specifies the number of replacements (optional). |
string.find(str, substr, [init, [end]]) | Searches for substr within str and returns the starting and ending indices of the found substring, or nil if not found. |
string.reverse(arg) | Reverses the string. |
string.format(...) | Returns a formatted string similar to printf . |
string.char(arg) and string.byte(arg[, int]) | char converts an integer to a character, and byte converts a character to its integer value (default is the first character). |
string.len(arg) | Returns the length of the string. |
string.rep(string, n) | Returns n copies of the string. |
.. | Concatenates two strings. |
string.gmatch(str, pattern) | Returns an iterator function that yields the next substring matching pattern found in str . |
string.match(str, pattern, init) | Finds the first match in str for pattern and returns captured results; if no match is found, returns nil . |
string.sub(s, i [, j]) | Extracts a substring from s , starting at i and ending at j (default is -1 , the last character). |
Example:
str = "Lua"
print(string.upper(str)) -- Converts to uppercase: LUA
print(string.lower(str)) -- Converts to lowercase: lua
print(string.reverse(str)) -- Reverses the string: aul
print(string.len("abc")) -- Length of "abc": 3
print(string.format("the value is: %d", 4)) -- Formatted output: the value is: 4
print(string.rep(str, 2)) -- Copies the string twice: LuaLua
string1 = "cn."
string2 = "dobot"
string3 = ".cc"
print("Connected string: ", string1 .. string2 .. string3) -- Concatenates strings: cn.dobot.cc
string1 = [[aaaa]]
print(string.gsub(string1, "a", "z", 3)) -- Replaces in the string: zzza
print(string.find("Hello Lua user", "Lua", 1)) -- Searches for "Lua", prints indices: 7, 9
sourcestr = "prefix--runoobgoogletaobao--suffix"
sub = string.sub(sourcestr, 1, 8) -- Extracts the prefix
print("\nExtracted: ", string.format("%q", sub)) -- Prints: Extracted: "prefix--"
Tables
A table
is a collection of data with associated indices.
The simplest constructor is {}
, which creates an empty table. Tables can be directly initialized.
Tables are essentially associative arrays, allowing any type of value to be used as an index, except nil
.
Tables are dynamically sized and can be resized as needed.
You can retrieve the length of a table using the #
operator.
tbl = {[1] = 2, [2] = 6, [3] = 34, [4] = 5}
print("Table length: ", #tbl) -- Prints: 4
Lua provides many methods for table manipulation:
Method | Description |
---|---|
table.concat(table [, sep [, start [, end]]]) | Concatenates elements of the specified table from start to end , using the optional separator sep . |
table.insert(table, [pos,] value) | Inserts value at position pos in the table (default is at the end). |
table.remove(table [, pos]) | Removes and returns the element at position pos in the table (default is the last element). |
table.sort(table [, comp]) | Sorts the given table in ascending order. |
Example 1:
fruits = {} -- Initialize table
fruits = {"banana", "orange", "apple"} -- Assign values
print("Concatenated string: ", table.concat(fruits, ", ", 2, 3)) -- Concatenates specified indices: orange, apple
-- Insert at the end
table.insert(fruits, "mango")
print("Element at index 4: ", fruits[4]) -- Prints: Element at index 4: mango
-- Insert at index 2
table.insert(fruits, 2, "grapes")
print("Element at index 2: ", fruits[2]) -- Prints: Element at index 2: grapes
print("Last element: ",
fruits[5]) -- Prints: Last element: mango
table.remove(fruits)
print("Last element after removal: ", fruits[5]) -- Prints: Last element after removal: nil
Example 2:
fruits = {"banana", "orange", "apple", "grapes"}
print("Before sorting:")
for k, v in ipairs(fruits) do
print(v) -- Prints: banana orange apple grapes
end
-- Sort in ascending order
table.sort(fruits)
print("After sorting:")
for k, v in ipairs(fruits) do
print(v) -- Prints: apple banana grapes orange
end
Arrays
An array is a collection of elements of the same data type arranged in a specific order. Arrays can be one-dimensional or multi-dimensional.
One-Dimensional Array:
The simplest array, whose logical structure is a linear list.
Multi-Dimensional Array:
An array that contains other arrays, with each index corresponding to an array.
Example 1: One-Dimensional Array
You can use a for
loop to iterate through the elements of a one-dimensional array. Accessing an index that has no value returns nil
.
array = {"Lua", "Tutorial"} -- Create a one-dimensional array
for i = 0, 2 do
print(array[i]) -- Prints: nil Lua Tutorial
end
-- In Lua, the index value starts at 1, but you can also specify 0. Additionally, negative numbers can be used as array indices.
array = {}
for i = -2, 2 do
array[i] = i * 2 + 1 -- Assign values to the one-dimensional array
end
for i = -2, 2 do
print(array[i]) -- Prints: -3 -1 1 3 5
end
Example 2: A 3x3 Multi-Dimensional Array
-- Initialize the array
array = {}
for i = 1, 3 do
array[i] = {}
for j = 1, 3 do
array[i][j] = i * j
end
end
-- Access the array
for i = 1, 3 do
for j = 1, 3 do
print(array[i][j]) -- Prints: 1 2 3 2 4 6 3 6 9
end
end