lua syntax tutorail||doc136841

September 20, 2022

1 lua basic syntax

1.1 Notes

1: Single line comment

Two minus signs are single-line comments

--

2: Multi-line comments

--[[
 Multiline Comment
 Multiline Comment
 ]]--

1.2 Identifiers

The identifier is used to define a variable, and the function gets other user-defined items. The identifier starts with a letter A to Z or a to z or an underscore _ followed by 0 or more letters, underscores, and numbers (0 to 9).

It is best not to use the underscore to increase the letter identifier, because Lua's reserved words are also like this.

Special characters such as @, $, and% are not allowed to define identifiers. Lua is a case-sensitive programming language. Therefore, Runoob and runoob are two different identifiers in Lua. Some of the correct identifiers are listed below:

mohd         zara      abc     move_name    a_123
myname50     _temp     j       a23b9        retVal

1.3 Key words

The reserved keywords of Lua are listed below. Reserved keywords cannot be used as constants or variables or other user-defined identifiers:

and break do else
elseif end false for
function if in local
nil not or repeat
return then true until
while goto


1.4 Variables

It is a dynamically typed language. Variables don't need to be type defined, just assign values ​​to variables. Values ​​can be stored in variables, passed as parameters or returned as results.

  • In order to avoid polluting the whole world, we generally define variables using the local keyword, such as:
    Due to the grammatical characteristics of Lua, variables can store any type of value, so what value we give it, it is what value

1.5 Data Types

DataType Description
nil This one is the simplest, only the value nil belongs to this class, indicating an invalid value (equivalent to false in a conditional expression)
boolean Contains two values: false and true
number Represents a real floating-point number of type double
string Strings are represented by a pair of double or single quotes
function Functions written in C or Lua
userdata Represents an arbitrary C data structure stored in a variable
thread Represents an independent line of execution for executing coroutines
table A table in Lua is actually an "associative array", and the index of the array can be of number, string or table type. In Lua, table creation is done through "construction expressions". The simplest construction expression is {}, which is used to create an empty table.

We can test the type of a given variable or value using the type function:

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

nil (empty)

The nil type means that there is no valid value, it has only one value – nil, for example printing a variable with no assignment will output a nil value:

local a
print(type(a)) -- the output is: nil

For global variables and tables, nil also has a "delete" function. Assigning a nil value to a global variable or a variable in the table table is equivalent to deleting them. Execute the following code to know:

local tab1 = { key1 = "val1", key2 = "val2", "val3" }
for k, v in pairs(tab1) do
    print(k .. " - " .. v)
end

tab1.key1 = nil
for k, v in pairs(tab1) do
    print(k .. " - " .. v)
end

boolean (Boolean)

The boolean type has only two optional values: true (true) and false (false). Lua treats false and nil as false, everything else is true, and the number 0 is also true:

print(type(true))
print(type(false))
print(type(nil))

if false or nil then 
 print("At least one is true")
else
 print("false and nil are both false")
end
if 0 then
 print("Number 0 is true")
else
 print("Number 0 is false")
end

The result of executing the above code is as follows:

boolean
boolean
nil
false and nil are both false
Number 0 is true

number

Lua has only one number type by default – double (double precision) type (the default type can be modified in the definition in luaconf.h), the following types of writing are regarded as number type:

print(type(2))
print(type(2.2))
print(type(0.2))

The result of executing the above code:

number
number
number

string (string)

Strings are represented by a pair of double or single quotes.

local string1 = "this is string1"
local string2 = 'this is string2'

You can also use 2 square brackets "[[]]" to denote a "block" of string.

local html = [[

head>

    Novice Tutorial
body>
html>
]]
print(html)

The result of executing the following code is:

head>

    Novice Tutorial
body>
html>

When performing arithmetic operations on a string of numbers, Lua will try to convert the string of numbers into a number:

print("2" + 6) --The output is: 8
print("2" + "8") --The output is: 8

String concatenation uses .. , as in:

print("a" .. 'b') -- the output is: ab
print(157 .. 428) -- the output is: 157428

Use # to calculate the length of the string and put it before the string, as in the following example:

local len = "www.runoob.com"
print(#len) --The output is: 14

table

In Lua, table creation is done through "construction expressions". The simplest construction expression is {}, which is used to create an empty table. You can also add some data to the table and initialize the table directly:

-- create an empty table
local tbl1 = {}

-- direct initial table
local tbl2 = {"apple", " pear", "orange", "grape"}

A table in Lua is actually an "associative array", similar to a key-value pair, the value can be found through the key, and the key can be a number or a string.

local a = {}
a["key"] = "value" -- use the string 'key' as the key 
local key = 10 -- declare a variable named key, Has nothing to do with the string 'key' above 
a[key] = 22 
a[key] = a[key] + 11
for k, v in pairs (a) do --traverse the elements in the table 
 print(k .. " : " .. v)
end

The script execution result is:

key : value
10 : 33

Unlike arrays in other languages, which use 0 as the initial index of the array, the default initial index of a table in Lua generally starts with 1.

local tbl = {"apple", "pear", "orange", "grape"}
for key, val in pairs(tbl) do
    print("Key", key)
end

The script execution result is:

Key    1
Key    2
Key    3
Key    4

The table does not have a fixed size. When new data is added, the length of the table will automatically increase. The original table is nil.

local a3 = {}
for i = 1, 10 do
    a3[i] = i
end
a3["key"] = "val"
print(a3["key"])
print(a3["none"])

The script execution result is:

val
nil

table set table

local a = {}
a['childTB1'] = {} -- add the key as 'childTB1', the value is the data of the empty table 
a['childTB1']['Key '] = 1 
print(a['childTB1']['Key'])

The script execution result is:

1

function

In Lua, functions are considered "First-Class Values", and functions can be stored in variables:

function factorial1(n)
    if n == 0 then
        return 1
    else
        return n * factorial1(n - 1)
    end
end
print(factorial1(5))
factorial2 = factorial1
print(factorial2(5))

The script execution result is:

120
120

A function can be passed as an anonymous function parameter:

local function testFun(tab,fun)

The script execution result is:

key1 = val1
key2 = val2

2 Table usage and methods

A table is a Lua data structure used to help us create different data types, such as: arrays, dictionaries, etc.

Lua table uses associative arrays. You can use any type of value to index into the array, but this value cannot be nil.

The size of Lua table is not fixed, you can expand it according to your needs.


table construction

-- Initialize table 
local mytable = {}

-- Specify value 
mytable[1]= "Lua"

-- remove reference 
mytable = nil

When we set the elements for table a and then assign a to b, both a and b point to the same memory. If a is set to nil , then b can also access the elements of the table. If no specified variable points to a, Lua's garbage collection mechanism will clean up the corresponding memory.

The following example demonstrates the situation described above:

-- simple table
local mytable = {}
print("The type of mytable is ",type(mytable))

mytable[ 1]= "Lua"
mytable["wow"] = "Before modification"
print("The element with index 1 of mytable is", mytable[1])
print("The element whose index is wow in mytable is ", mytable["wow"])

-- alternatetable and mytable refer to the same table[
 local alternatetable = mytable

print("The element at index 1 of the alternatetabletable is ", alternatetable[1])
print("The element at index wow in mytable is " , alternatetable["wow"])

alternatetable["wow"] = "modified"

print("mytable index is wow The element of is ", mytable["wow"])

-- free variable 
alternatetable = nil
print("alternatetable is", alternatetable)

-- mytable is still accessible 
print("The element at index wow of mytable is ", mytable["wow"])

mytable = nil
print("mytable is", mytable)

The result of executing the above code is:

The type of mytable is table
mytable element with index 1 is Lua
mytable element with index wow is before modification 
alternatetable element with index 1 is Lua[[ []]]mytable element with index wow is before modification 
mytable element with index wow is after modification 
alternatetable is nil
mytable element with index wow is After modification 
mytable is nil

table operations

Method Use
table.concat (table [, sep [, start [, end]]]) It is the abbreviation of concatenate (concatenation, connection). The table.concat() function lists all the elements from the start position to the end position of the array part of the specified table in the parameter, and the elements are separated by the specified separator (sep).
table.insert (table, [pos,] value) Insert an element of value at the specified position (pos) of the array part of the table. The pos parameter is optional, and the default is the end of the array part
table.remove (table [, pos]) Returns the element at position pos in the part of the table array. The following elements will be moved forward. The pos parameter is optional, and the default is the length of the table, which is deleted from the last element.
table.sort (table [, comp]) Returns the string after table concatenation


table connection

local fruits = {"banana","orange","apple"}
-- return the concatenated string of table
print("Concatenated string",table.concat (fruits))

-- Specify the connection character 
print("Concatenated string",table.concat(fruits,", "))

-- Specify the index to concatenate table
print("Concatenated string",table.concat(fruits,", ", 2,3))

The output of executing the above code is:

concatenated string bananaorangeapple
 concatenated string banana, orange, apple
 concatenated string orange, apple

table insertion and removal

The following examples demonstrate table insert and remove operations:

local fruits = {"banana","orange","apple"}

-- insert  at the end
table.insert(fruits,"mango")
print("The element at index 4 is ",fruits[4])

-- insert 
table at the key at index 2 .insert(fruits,2,"grapes")
print("The element with index 2 is ",fruits[2])

print("The last The element is ",fruits[5])
table.remove(fruits)
print("The last element after removal is ",fruits[5])

The output of executing the above code is:

The element with index 4 is mango
 The element with index 2 is grapes
 The last element is mango
 The last element after removal is nil

table sorting

local fruits = {"banana","orange","apple","grapes"}
print("Before sorting")
for k,v in ipairs(fruits) do
    print(k,v)
end

table.sort(fruits)
print("After sorting")
for k,v in ipairs(fruits) do
    print(k,v)
end

The output of executing the above code is:

Before sorting
1 banana
2 orange
3 apple
4 grapes
After sorting
1 apple 
2 banana
3 grapes
4 orange