Lua Upper Half Road

Keywords: lua

Lua

Lua is a lightweight, compact scripting language written in standard C and open to source code. It is designed to be embedded in applications to provide flexible extension and customization capabilities for applications.

Features of Lua

  1. Lightweight: Written in standard C and open to source code, compiled at just over 100 K and easily embedded in applications
  2. Extensibility: Lua provides very easy-to-use extension interfaces and mechanisms: provided by the host language (mainly C and C++), Lua can use them as if they were built-in
  3. Other features:
  • Supports process-oriented and functional programming
  • Automatic memory management: Provides only one common type of table that can be used to implement arrays, hash tables, collections, objects
  • Language built-in pattern matching;closure;A function can be viewed as a value;Provides multithreaded support (collaborative processes, not threads supported by the operating system)
  • Closures and table s make it easy to support some of the key mechanisms required for object-oriented programming, such as data abstraction, virtual functions, inheritance, and overloading

Scenarios for Lua

  • Game Development
  • Develop scripts independently
  • web application script
  • Extensions and database plug-ins: MySql Proxy and MySQL WorkBench
  • Security systems, such as intrusion detection systems

Lua Basic Grammar

Lua programming

Lua programming supports two forms of programming, interactive and scripted

Lua interactive programming mode can be enabled by commands lua-i or lua:

$ lua -i 
$ Lua 5.3.0  Copyright (C) 1994-2015 Lua.org, PUC-Rio
> print("Hello World!")
Hello World!
>

Lua scripting refers to saving Lua program code to a file ending in Lua and executing it.

#!/usr/local/bin/lua
print("Hello World!")

Lua's interpreter/usr/local/bin/lua is specified in the code above.Adding a # tag to the interpreter will ignore it.

Notes

Single-line and multi-line comments

--print("Hello World")
--[[
print("Shanghai")
print("Huangpu District")
--]]
print("hello,world".."Hello World")

The execution code is

hello,world Hello World

identifier

The Lua identifier is used to define a variable.Indicator with a letter A-Z or A-Z or underscore_Start with 0 or more letters, underscores, and numbers (0-9).

  • Cannot start with a number
  • Can't be a keyword
  • Avoid identifiers that consist of "underscore + uppercase letters" (reserved in lua, with special usage and general convention for global variables within Lua)

Keep keywords

andbreakdoelse
elseifendfalsefor
functionifinlocal
nilnotorrepeat
returnthentrueuntil
whilegoto

global variable

By default, variables are always considered global in Lua.A global variable does not need to be declared. Assigning a variable creates it. It is also good to access a global variable without an initial statement, but the result is: nil.

If you want to delete a global variable, you just assign it nil.

This variable exists only if and only if it is not equal to nil.

--Accessing an uninitialized global variable
print(b)
--Create a global variable C
c = 100
print(c)
--Delete a global variable
c = nil
print(b)

The result of executing the code is:

nil
100
nil

Lua data type

Lua is a dynamic language type. Variables do not need to be defined as a type, they only need to be assigned values.Values can be stored in variables and passed as parameters or returned as results.

There are eight basic data types in Lua: nil, boolean, number, string, userdata, function, thread, table.

nil (empty)

The nil type represents a value that has no valid value but only one value: nil.

For global variables and tables, nil also has a delete effect.Assigning a nil to a global variable or a variable in a table table is equivalent to deleting the variable.

tab1 = {  "val1",  "val2", "val3" }
for k, v in pairs(tab1) do
    print(k .. " - " .. v)
end
print("************") 
tab1[1] = nil
for k, v in pairs(tab1) do
    print(k .. " - " .. v)
end

The result of executing the code is:

1 - val1
2 - val2
3 - val3
************
2 - val2
3 - val3

tabl[1] = nil, is equivalent to deleting the first variable in table tab 1

When nil is used as a comparison, double quotation marks''should be added

print(type(X))
print(type(X)==nil)
print(type(X)=="nil")

The result of executing the code is:

nil
false
true

The type() function returns a string of "nil" when it tests the uninitialized global variable X.Is a string type, then a double quotation mark''is required when comparing with nil.

boolean

The boolean type has only two optional values: true or false.In Lua, false and nil are considered false, others are true, and the number 0 is 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 All for false")
end

if 0 then
    print("The number 0 is true")
else
    print("Number 0 is false")
end

The result of executing the code is:

boolean
boolean
nil
false and nil All for false
 The number 0 is true

Number (number)

There is only one number Type by default in Lua: double, which modifies the definition in luaconf.h.

print(2e-1)
print(2e-2)
print(2e-3)
print(2e+0)
print(2e+1)
print(2e+2)
print(2e+3)
print("*************")
print(type(2))
print(type(2.2))
print(type(0.2))
print(type(2e+1))

The result of execution is:

0.2
0.02
0.002
2.0
20.0
200.0
2000.0
*************
number
number
number
number

String (string)

String is represented by a pair of double or single quotes.You can also use two square brackets to represent a string [[]].

stringA = 'hello,world'
stringB = "hello,china"
stringC = [[www hello,hello www]]
print(stringA)
print(stringB)
print(stringC)

Code execution results:

hello,world
hello,china
www hello,hello www

When an arithmetic operation is performed on a numeric string, the string is converted to a number

strNumA = "5"
strNumB = "55"
print(type(strNumA))
print(type(strNumB))
resA = strNumA + 5
resB = strNumB + 5
resC = strNumA - 5
resD = strNumB - 5
resE = strNumA * 5
resF = strNumB / 5
resG = strNumB + strNumA 
print("Result:"..resA.."The type is:"..type(resA))
print("Result:"..resB.."The type is:"..type(resB))
print("Result:"..resC.."The type is:"..type(resC))
print("Result:"..resD.."The type is:"..type(resD))
print("Result:"..resE.."The type is:"..type(resE))
print("Result:"..resF.."The type is:"..type(resF))
print("Result:"..resG.."The type is:"..type(resG))

The result of execution is:

string
string
 Results: The 10 types are: number
 Results: The 60 types are: number
 Result: Type 0 is: number
 Results: The 50 types are: number
 Results: The 25 types are: number
 Results: 11.0 The type is: number
 Results: The 60 types are: number

In lua, when a numeric string is +, -, *, /arithmetic, it is converted to a number and then to an arithmetic operation.

String length calculation using #

strA = "wwwhelloworldwww"
print("strA The length is:"..#strA)

The result of execution is:

strA Length is: 16

table

In Lua, the simplest form of expression {} created when a table is created is to create an empty table.You can add some data directly to the table and initialize the table directly.A table is actually an associated array whose index can be a number or a string, and its default initial index subscript starts at 1, unlike other languages, its default initial index starts at 0.

Tables do not have fixed length sizes, and they grow automatically when new data is added.All uninitialized table s are nil.

tbl = {"apple", "pear", "orange", "grape"}
for key, val in pairs(tbl) do
    print("Key", key,val)
end
--Add new data to the table
tbl[5] = "addNew"
for key, val in pairs(tbl) do
    print("Key", key,val)
end
--Uninitialized data in table
print(tbl[6])

The result of executing the code is:

Key	1	apple
Key	2	pear
Key	3	orange
Key	4	grape
Key	1	apple
Key	2	pear
Key	3	orange
Key	4	grape
Key	5	addNew
nil

Function (function)

In Lua, functions are considered "First-Class Value", and functions can exist in variables.

function factorial1(n)
    if n == 0 then
        return 1
    else
        return n * factorial1(n - 1)
    end
end
print("function factorial1 Return value:"..factorial1(5))
factorial2 = factorial1
print("variable factorial2 Value of:"..factorial2(5))

The result of executing the code is:

function factorial1 Return value: 120
 variable factorial2 Value of: 120

factorial2 = factorial1,

Assign the return value of the factorial1 function to the variable factorial2, and the return value of the factorial1 (n) function is the factorial that returns n: n!.

thread

The main thread in Lua is the coroutine.Similar to threads, it has its own separate stack, local variables, and instruction pointers and can share global variables and most other things with other collaborators.

The difference between a thread and a process: Threads can run more than one at a time, and a running process can only be suspended if suspended.

userdata (custom type)

userdata is user-defined data that represents a type created by an application or a C/C++ language library and can store data of any C/C++ data type (usually struct and pointer) in a Lua variable for invocation.

Lua variable

There are three types of Lua variables: global variables, local variables, and fields in tables.

Before a variable can be used, it needs to be declared in code, that is, created.Variables in Lua are global variables, either in statement blocks or in functions.Only variables declared with local display are local variables.The scope of a local variable starts at the declared position and ends at the statement block in which the variable resides.The default values for variables are nil.

a = 5               -- global variable
local b = 5         -- local variable

function joke()
    c = 5           -- global variable
    local d = 6     -- local variable d Scope to end End
end

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

do
    local a = 6     -- local variable
    b = 6           -- Re-assigning local variables
    print(a,b);     --> 6 6
end

print(a,b)      --> 5 6

Code execution results:

5	nil
6	6
5	6

Variable assignment

Lua can assign values to multiple variables at the same time.The elements of the variable list and the value list are separated by commas. The assignment statement calculates the value on the right and then performs the assignment operation, assigning the value to the variable on the left.

If multiple variables are to be assigned, each variable must be assigned in turn.

When the number of variables and the number of values are inconsistent, Lua always takes a strategy based on the number of variables:

  • Number of Variables > Number of Values, Complete nil by the value corresponding to the number of variables
  • Number of variables < number of values, extra values will be ignored

Multivalue assignments are often used to swap variables or return function calls to variables

a,b = 1,2
print(a,b)

--Number of variables>Number of values, if insufficient, complement nil
A,B,C = 3,4
print(A,B,C)

--Number of variables<Number of values, extra values are ignored
aa,bb = 11,22,33
print(aa,bb)

--Multivalue assignment of function return value
function func1(n)
    return n,n-1
end

AA,BB = func1(6)
print(AA,BB)

--Multivalue assignment must assign values in turn
e,f,g = 0
print(e,f,g)
E,F,G = 0,0,0
print(E,F,G)

Code execution results:

1	2
3	4	nil
11	22
6	5
0	nil	nil
0	0	0

Local variables should be used whenever possible

  1. Avoid Naming Conflicts
  2. Accessing local variables is faster than global variables

Lua Process Control

The process control statements of the Lua programming language are set by programming one or more conditional statements.Executes the specified program code when the condition is true and other code when false.

The expression result of the control structure can be any value, false and nil are considered false, true and non-nil are considered true in Lua.

--A condition indicates that the result value is false and nil Do not execute the conditional statement
if (false)
then
    print("Conditional expression result: false True")
else
    print("Conditional expression result: false False")
end

if (nil)
then
    print("Conditional expression result: nil True")
else
    print("Conditional expression result: nil False")
end

--0 The value of the result of the expression is true
if (0)
then
    print("Conditional expression result: 0 is true")
else
    print("Conditional expression result: 0 is false")
end

Code execution results:

Conditional expression result: false False
 Conditional expression result: nil False
 Conditional expression result: 0 is true

Lua function

In Lua, functions are the main way to abstract statements and expressions.There are two uses of the Lua function:

  1. Completes the specified task, which is used as a call statement to execute the specified task.
  2. Calculates the return value, in which case the function is used as an expression of the assignment statement.

Lua function definition format

optional_function_scope function function_name( argument1, argument2, argument3..., argumentn)
    function_body
    return result_params_comma_separated
end

optional_function_scope: sets whether the Lua function is a global or a local function, defaults to a global function if no parameters are set, and if set to a local function, sets the parameter local to specify that the function is a local function

function_name: function name

(argument1, argument2, argument3..., argumentn): Function parameters, if more than one parameter can be separated by commas, can be taken without parameters

function_body: the body of a function, the block of code in a function that needs to be executed

result_params_comma_separated: The return value of the function, the Lua function can return multiple values, separated by commas

Lua function call

--[[   Lua Calls to functions max Get Maximum  --]]
function  max(num1,num2)
    if(num1 > num2)
    then
        result = num1
    else
        result = num2
    end
    return result
end

print("Compare sizes of 4 and 6,The biggest is:"..max(4,6))
print("Compare 4, 2.51 Size,The biggest is:"..max(4,2.51))

The result of executing the code is:

Compare sizes of 4 and 6,The biggest is:6
 Compare 4, 2.51 Size,The biggest is:4

Lua function as a function parameter

myprint = function(param)
   print("This is a print function -   ##",param,"##")
end

function add(num1,num2,functionPrint)
   result = num1 + num2
   -- Call passed function parameters
   functionPrint(result)
end
myprint(10)
-- myprint Functions are passed as parameters
add(2,5,myprint)

The result of executing the code is:

This is a print function -   ##	10	##
This is a print function -   ##	7	##

Multiple Return Values of Lua Function

function maximum (a)
    local mi = 1             -- Maximum Index
    local m = a[mi]          -- Maximum
    for i,val in ipairs(a) do
       if val > m then
           mi = i
           m = val
       end
    end
    return m, mi
end

maxNum,maxIndex = maximum({8,10,23,12,5})

print("The maximum is:"..maxNum,"Maximum Subscript:"..maxIndex)

The result of executing the code is:

Maximum value is: 23	Maximum Subscript:3

Variable parameters of Lua function

The Lua function accepts a variable number of parameters and is represented by'...'in the parameter list.

The Lua function can accept fixed + variable parameters.

function add(...)  
local s = 0  
  for i, v in ipairs{...} do   --> {...} Represents an array of all variable length parameters  
    s = s + v  
  end  
  return s  
end  
print("The cumulative sum is:"..add(3,4,5,6,7))  --->25

The result of executing the code is:

The cumulative sum is: 25

Usually when traversing variable length parameters, you only need to use {...} and then variable length parameters may contain some nil, so you can use the select function to access variable length parameters.

  • select ("#",...): Returns the length of a variable parameter
  • select(n,...): Returns a list of all parameters from start n to end
  • The fixed argument to'#'or'n' passed in from the select function is called a selector, and different selector functions correspond to different selector functions.

select("n",...): Gets a list of parameters specifying the start to end position

function f(...)
    a,b = select(3,...)  -->From the third position, variable a The first parameter corresponding to the list of variables on the right
    print ("The first value in the list of variables:",a)
    print ("The first two values in the variable list:",a,b)
    print ("All values in the variable list:",select(3,...)) -->Print all list parameters
end

f(0,1,2,3,4,5)

The result of executing the code is:

The first value in the list of variables:	2
 The first two values in the variable list:	2	3
 All values in the variable list:	2	3	4	5

select ('#',...) to get variable parameter length

do  
    function foo(...)  
        for i = 1, select('#',...) do --> Get the total number of parameters
            local arg = select(i, ...); -->Read parameters, arg Corresponds to the first parameter in the list of variables on the right
            print("arg", arg);  
        end  
    end  
 
    foo(1, 2, 3, 4);  
end

The result of executing the code is:

arg	1
arg	2
arg	3
arg	4

There is no special meaning for do...end, but to execute a statement block, which is equivalent to {} in C/C++. Local variables in it can only be referenced in the latest do...end statement block, and references outside the statement block are invalid.

Lua Operator

Operators are special symbols that tell the interpreter to perform specific mathematical or logical operations.The types of operators in Lua can be divided into the following: arithmetic, relational, logical, and other operators.

Arithmetic Operators

Operators are: +, -, *, /,%, ^ (power), -(minus sign)

a = 21
b = 10
c = a + b
print("Line 1 - c The value of ", c )
c = a - b
print("Line 2 - c The value of ", c )
c = a * b
print("Line 3 - c The value of ", c )
c = a / b
print("Line 4 - c The value of ", c )
c = a % b
print("Line 5 - c The value of ", c )
c = a^2
print("Line 6 - c The value of ", c )
c = -a
print("Line 7 - c The value of ", c )

Code execution results:

Line 1 - c The value of 	31
Line 2 - c The value of 	11
Line 3 - c The value of 	210
Line 4 - c The value of 	2.1
Line 5 - c The value of 	1
Line 6 - c The value of 	441.0
Line 7 - c The value of 	-21

Relational Operators

Operators are: ==, ~= (not equal), >, <, >=, <=

a = 21
b = 10

print("a The value is:",a)
print("b The value is:",b)
if( a == b )
then
   print("Line 1 - a Be equal to b" )
else
   print("Line 1 - a Not equal to b" )
end
if( a ~= b )
then
   print("Line 2 - a Not equal to b" )
else
   print("Line 2 - a Be equal to b" )
end
if ( a < b )
then
   print("Line 3 - a less than b" )
else
   print("Line 3 - a Greater than or equal to b" )
end
if ( a > b )
then
   print("Line 4 - a greater than b" )
else
   print("Line 5 - a Less than or equal to b" )
end
-- modify a and b Value of
a = 5
b = 20
if ( a <= b )
then
   print("Line 5 - a Less than or equal to  b" )
end
if ( b >= a )
then
   print("Line 6 - b Greater than or equal to a" )
end

Code execution results:

a The value is:	21
b The value is:	10
Line 1 - a Not equal to b
Line 2 - a Not equal to b
Line 3 - a Greater than or equal to b
Line 4 - a greater than b
Line 5 - a Less than or equal to  b
Line 6 - b Greater than or equal to a

Logical operators

Operators are: and, or, not (logical non)

a = true
b = true

print("a For:",a)
print("b For:",b)

if ( a and b )
then
   print("a and b - Conditions are true" )
end

if ( a or b )
then
   print("a or b - Conditions are true" )
end

print("---------Split Line---------" )

-- modify a and b Value of
a = false
b = true

if ( a and b )
then
   print("a and b - Conditions are true" )
else
   print("a and b - Conditions are false" )
end

if ( not( a and b) )
then
   print("not( a and b) - Conditions are true" )
else
   print("not( a and b) - Conditions are false" )
end

Code execution results:

a For:	true
b For:	true
a and b - Conditions are true
a or b - Conditions are true
---------Split Line---------
a and b - Conditions are false
not( a and b) - Conditions are true

Other operators (#,...)

Join operator'...'or string length operator #' in Lua

a = "Hello "
b = "World"
c = 5

print("a Value of:",a)
print("b Value of:",b)
print("c Value of:",c)

d = b..5  -->First put number convert to string,Then proceed..Join operation

print("d The value is:",d)
print("c The type of is:",type(c))
print("d The type of is:",type(d))

print("Connection String a and b ", a..b )

print("b String Length ",#b )

print("Character string Test length ",#"Test" )

The result of code execution is:

a Value of:	Hello 
b Value of:	World
c Value of:	5
d The value is:	World5
c The type of is:	number
d The type of is:	string
 Connection String a and b 	Hello World
b String Length 	5
 Character string Test length 	4

... is the operator that joins two strings, which is converted to a string and then joined when one of them is a number Type

Operator Priority

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

Lua String

String Usage

A string or string is a string of numbers, letters, and underscores.

Representation of strings:

A string of characters between single quotes

A string of characters between double quotes

A string of characters between [[and]]

Escape characters are used for characters that cannot be displayed directly, converting double quotation marks'\''into strings.

string1 = 'Single Quote Representation'
print("string1:"..string1)
string2 = "Double quotation marks"
print("string2:"..string2)
string3 = [["Bracket Representation"]]
print("string3:"..string3)
string4 = "\"Escape Double Quotes\""
print("string4:"..string4)

Code execution results:

string1:Single Quote Representation
string2:Double quotation marks
string3:"Bracket Representation"
string4:"Escape Double Quotes"

String Operation

The Lua language provides many ways to support string manipulation.

Sequence NumberMethod & Purpose
1string.upper(argument): All strings are capitalized.
2string.lower(argument): All strings are lowercase.
3**string.gsub(mainString,findString,replaceString,num)** Replaces in a string.MainString is the string to be operated on, findString is the character to be replaced, replaceString is the character to be replaced, number of num replacements (ignore, replace all), such as: > string.gsub ("aaaa", "a", "z", 3);Zzza 3
4string.find (str, substr, [init, [end]) searches for the specified content in a specified target string (the third parameter is the index) and returns its location.Returns nil if it does not exist. >String.find ("Hello Lua user", "Lua", 1) 7 9
5string.reverse(arg) string inversion > string.reverse ("Lua") auL
6string.format(...) returns a printf-like formatted string > string.format("the value is:%d, 4) the value is:4
7string.char(arg) and string.byte (arg[, int]) chars convert integer numbers to characters and connect them, and byte to integer values (you can specify a character, the default first character). >String.char (97,98,99,100) ABCD > string.byte ("ABCD", 4) 68 > string.byte ("ABCD") 65 >
8string.len(arg) calculates the length of the string.string.len("abc") 3
9string.rep(string, n) returns N copies of string > string.rep (abcd, 2) ABCD ABCD
10... link two strings > Print ("www.runoob.". "com") www.runoob.com
11string.gmatch(str, pattern) returns an iterator function that is called each time, returning the next patterned substring found in the string str.If the string described by the parameter pattern is not found, the iteration function returns nil. >For word in string.gmatch ("Hello Lua user", "%a+") do print (word) end Hello Lua user
12string.match(str, pattern, init) string.match() only looks for the first pair in the source string str. The parameter init is optional, specifying the starting point of the search process, defaulting to 1.When pairing succeeds, the function returns all captured results in the pairing expression.If no capture tag is set, the entire pairing string is returned. When no successful pairing occurs, nil is returned. > =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"

substr

string.sub() is the interception method for strings.The prototype I s: string.sub(s, i[, j]

  • s: The string to intercept
  • i: the location of the intercept
  • j: End position of intercept, default to -1, last character
-- Character string
local sourcestr = "prefix--runoobgoogletaobao--suffix"
print("\n Original string", string.format("%q", sourcestr))

-- Interception section, 1st to 15th
local first_sub = string.sub(sourcestr, 4, 15)
print("\n First intercept", string.format("%q", first_sub))

-- String prefix, first to eighth
local second_sub = string.sub(sourcestr, 1, 8)
print("\n Second intercept", string.format("%q", second_sub))

-- Intercept the last 10
local third_sub = string.sub(sourcestr, -10)
print("\n Third intercept", string.format("%q", third_sub))

-- Index out of bounds, output original string
local fourth_sub = string.sub(sourcestr, -100)
print("\n Fourth intercept", string.format("%q", fourth_sub))

The result of code execution is:

Original string	"prefix--runoobgoogletaobao--suffix"

First intercept	"fix--runoobg"

Second intercept	"prefix--"

Third intercept	"ao--suffix"

Fourth intercept	"prefix--runoobgoogletaobao--suffix"

String Formatting

Lua provides the string.format() function to generate a string with a specific format. One parameter of the function is the format, followed by the data in the corresponding format.Similar to printf in C, it improves the readability of strings.The format string may contain the following escape codes.

%c - Accept a number, And convert it to ASCII Corresponding Characters in Code Table
%d, %i - Accept a number and convert it to a signed integer format
%o - Accept a number and convert it to octal format
%u - Accept a number and convert it to unsigned integer format
%x - Accept a number and convert it to hexadecimal format, Use lowercase letters
%X - Accept a number and convert it to hexadecimal format, Using Capital Letters
%e - Accept a number and convert it into a scientific notation format, Use lowercase letters e
%E - Accept a number and convert it into a scientific notation format, Using Capital Letters E
%f - Accept a number and convert it to floating point format
%g(%G) - Accept a number and convert it to%e(%E, Corresponding%G)and%f A shorter format in
%q - Accepts a string and converts it to safe by Lua Compiler Read-in Format
%s - Accepts a string and formats it with the given parameters

Formatting can be refined by adding parameters after%

(1) Symbol: One+A sign indicates that the following numeric escape character will cause positive numbers to show a positive sign. Only negative numbers display symbols by default.
(2) placeholder: A 0, Placeholder when string width is specified later. The default placeholder when not filled is a space.
(3) Alignment Identification: When a string width is specified, Right alignment by default, increase-Number can be changed to left-aligned.
(4) Width value
(5) Decimal places/String Trimming: Decimal part added after width value n, If followed f(Floating-point escape character, as%6.3f)Sets that the decimal of the floating point number is reserved only n position, If followed s(String escape character, as%5.3s)Then set the string to display only before n position.
string1 = "Lua"
string2 = "Tutorial"
number1 = 10
number2 = 20
-- Basic string formatting
print(string.format("Basic Formatting %s %s",string1,string2))
-- DateFormatter
date = 2; month = 1; year = 2014
print(string.format("DateFormatter %02d/%02d/%06d", date, month, year))
print(string.format("DateFormatter %02d/%02d/%04d", date, month, year))
-- Decimal Formatting
print(string.format("%.4f",1/3))

Code execution results:

Basic Formatting Lua Tutorial
 Date format 02/01/002014
 Date format 02/01/2014
0.3333

Conversion of characters to integers

-- Character Conversion
-- Convert first character
print(string.byte("Lua"))
-- Convert the third character
print(string.byte("Lua",3))
-- Convert the first character at the end
print(string.byte("Lua",-1))
-- Second character
print(string.byte("Lua",2))
-- Convert the second character at the end
print(string.byte("Lua",-2))

-- integer ASCII Convert Code to Character
print(string.char(97))

The result of code execution is:

76
97
97
117
117
a

Match pattern

Matching patterns in Lua are described directly with regular strings.Used for pattern matching functions string.find,string.gmatch,string.gsub,string.match.

A character class is a pattern item that can match any character within a specific character set.For example, the character class%d matches any number.

All character classes supported by Lua:

  • . (dot): pair with any character

  • %a:Pair with any letter

  • %c: Pair with any controller (e.g. \n)

  • %d: Pair with any number

  • %l:Pair with any lowercase letter

  • %p: pair with any punctuation

  • %s: Pair with blank characters

  • %u: pair with any uppercase letter

  • %w: Pair with any letter/number

  • %x: Paired with any hexadecimal number

  • %z: Pair with any character representing 0

  • %x (where x is a non-alphabetic, non-numeric character): Pairs with the character X. Used primarily to handle functional characters in expressions (^$()%. []*+?)Pairing issues, such as%% pairing with%%

  • [several character classes]: pair with any character class contained in []. for example [%w_]With any letter/number, or underscore symbol ()Pair

s = "Deadline is 30/05/1999, firm"
date = "%d%d/%d%d/%d%d%d%d"
print(string.sub(s, string.find(s, date)))    --> 30/05/1999

-->'%A'Non-alphabetic characters
print(string.gsub("hello, up-down!", "%A", "."))

The result of code execution is:

30/05/1999
hello..up.down.	4

Lua Array

Arrays are elements of the same data type arranged in a certain order, and the index values of Lus arrays can be expressed as integers.We can access array elements through an integer index and return nil if we know the index has no value.Lua index values start with 1, but you can also specify 0.Negative numbers can also be used as index values.

array = {}

for i= -2, 2 do
   array[i] = i *2
end

for i = -2,2 do
   print(array[i])
end

The result of code execution is:

-4
-2
0
2
4

Lua iterator

Iterators are objects that can be used to traverse some or all of the Ancient Dragons in a standard template library container.Each Iterator object represents the exact address in the container.In Lua, an Iterator is a pointer-type structure that traverses every element of a collection.

Generic for iterator

The generic for holds the iteration function inside itself, but in fact it holds three values: the iteration function, the state constant, and the control variable.The generic for iterator provides a key/value pair of sets in the syntax:

for k, v in pairs(t) do
    print(k, v)
end
  • k,v: is a list of variables
  • paris (t): is a list of expressions
array = {"Google", "Runoob"}

for key,value in ipairs(array)
do
   print(key, value)
end

Code execution results:

1	Google
2	Runoob

The example above uses the iteration function ipairs(), which is provided by default in the Lua language.

Ipairs and pairs are built-in iterators in Lua to iterate over arrays in a loop.However, the difference is that ipairs stops iterating when it encounters the first element with a nil value, only for tables of array type;However, if you need to use a dictionary table or traverse to null values, pairs will not affect the iterator from iterating through the elements of the entire array, regardless of the presence of nil.

Execution of generic for:

  1. Initialize first, calculate the value of the expression after in, which should return three values required by the generic for: iteration function, state constant, control constant;As with multi-value assignments, if fewer than three returned values from an expression automatically add nil to the value, more values are ignored.
  2. Calling an iteration function with a state constant and a control constant as parameters (note that a state constant is of no use to a for structure, it is simply initializing to get its value and passing it to the iteration function)
  3. Assigning the return value of an iteration function to a list of variables
  4. If the first return value is nil, the loop ends, otherwise the loop body is executed
  5. Return to the second step to call the iteration function

A function is often used in Lua to describe an iterator that returns the next element of the set each time it is called.There are two main types of iterators in Lua.

  1. Stateless Iterator
  2. Multistate iterator

Stateless Iterator

Stateless iterators are iterators that do not retain any state, because in iteration we can use stateless iterators to avoid the extra cost of creating closures.For each iteration, the iteration function is called with the values of two variables (state and control variables) as parameters, and a stateless iterator uses only these two values to get the next element.

A typical simple example of this stateless iterator is iparis, which traverses every element of an array, with numeric values as needed for the element's index.

function square(iteratorMaxCount,currentNumber)
   if currentNumber<iteratorMaxCount
   then
      currentNumber = currentNumber+1
   return currentNumber, currentNumber*currentNumber
   end
end

for i,n in square,3,0
do
   print(i,n)
end

Code execution results:

1	1
2	4
3	9

The above is a simple iterator function that squares numbers. The iterator function square assigns the return value to the list of variables.

Multi-state iterator

Iterators need to hold multiple state information instead of simple state constants and control variables. The easiest way is to use closures. Another way is to encapsulate all state information into a table and use the table as the state constant for the iterator, since all information can be stored in this case, the iterator usually does not need a second parameter.

array = {"Google", "Runoob"}

function elementIterator (collection)
   local index = 0
   local count = #collection
   -- closures
   return function ()
      index = index + 1
      if index <= count
      then
         --  Returns the current element of the iterator
         return collection[index]
      end
   end
end

for element in elementIterator(array)
do
   print(element)
end

Code execution results:

Google
Runoob

The above example elementIterator uses a closure function: calculates the size of a collection and outputs various elements

Lua table

table is Lua's data structure that helps us create different types of data, such as arrays, dictionaries, and so on.

Lua table uses associative arrays, and you can index an array based on any type of value, but the index value cannot be nil.

Lua table s are of variable size and can be expanded to suit your needs.

Lua also uses table s to solve module s, package s, and object s

Construction of table s

Constructors are expressions that create and initialize tables.Tables are Lua's unique and powerful thing, and the simplest is the constructor {}, which creates an empty table

--Constructor creates empty table
mytable = {}
print("mytable The type of is:",type(mytable))

--Empty Table Add Element
mytable[1] = "Lua Test"
mytable["hello"] = "world"

--mytable Table assigns to altertable
altertable = mytable
print("altertable The type of is:",type(altertable))
print("altertable[1]:",altertable[1])
print("altertable[\"hello\"]:",altertable["hello"])

mytable = nil 
print("take mytable Set to nil")
print("altertable[1]:",altertable[1])
print("altertable[\"hello\"]:",altertable["hello"])

altertable = nil
print("take altertable Set to nil")
print("altertable[1]:",altertable[1])
print("altertable[\"hello\"]:",altertable["hello"])

Code execution results:

mytable The type of is:	table
altertable The type of is:	table
altertable[1]:	Lua Test
altertable["hello"]:	world
 take mytable Set to nil
altertable[1]:	Lua Test
altertable["hello"]:	world
 take altertable Set to nil
input:21: attempt to index a nil value (global 'altertable')

The example above creates an empty table, mytable, and sets the elements "Lua Test", "world".Then assign mytable to altertable, then both mytable and altertable point to the same block of memory, and when mytable = nil, altertable can also access elements through the index.If no variable points to a, that is, when both mytable and altertable are nil, Lua's garbage collection mechanism cleans up the corresponding memory.Mytable and altertable are null at this time, so the interpreter will report an error of "attempt to index a nil value", which cannot be indexed.

Operation of table

Lua provides many ways to support table operations, listing several common methods

Sequence NumberMethod & Purpose
1**table.concat (table [, sep [, start [, end]]])πŸ˜—*Concat is the abbreviation for concatenate. The table.concat() function lists all elements of the array part of the specified table in the parameter, from the start position to the end position, separated by the specified Sep.
2**table.insert (table, [pos,] value)πŸ˜—*Specify an element whose position (pos) insert value is value in the array part of the table. The POS parameter is optional and defaults to the end of the array part.
3**table.maxn(table)** Specifies the maximum key value of all positive key values in the table. If there is no element with a positive key value, it returns 0. (This method no longer exists after Lua5.2 and is implemented using custom functions in this article)
4**table.remove (table [, pos])** Returns the element whose table array is partially at the POS position. The element that follows is moved forward. The POS parameter is optional and defaults to the table length, which is deleted from the last element.
5**table.sort (table [, comp])** Sorts a given table in ascending order.

table connection

fruits = {"banana","apple","pear","orange"}
print("fruits The type of is:",type(fruits))

--Connect fruits
print("fruits.concat:",table.concat(fruits))

--Specify Connected Characters
print("Appoint\",\"Connected characters:",table.concat(fruits,","))

--Specify connection by index
print("Specify the connection character by index:",table.concat(fruits,",",2,4))

The result of code execution is:

fruits The type of is:	table
fruits.concat:	bananaapplepearorange
 Appoint","Connected characters:	banana,apple,pear,orange
 Specify the connection character by index:	apple,pear,orange

table insertion and removal

fruits = {"banana","apple","pear","orange"}
print("fruits The type of is:",type(fruits))

--Insert at the end by default if no location is specified
print("towards fruits in insert mango: ",table.insert(fruits,"mango"))
for k,v in ipairs(fruits) do
    print(k,v)
end

--Delete the specified location element
print("Delete the last element:",table.remove(fruits,#(fruits)))
for k,v in ipairs(fruits) do
    print(k,v)
end

--Delete location is not specified, default is table length
print("Delete the last element:",table.remove(fruits))
for k,v in ipairs(fruits) do
    print(k,v)
end

--Insert element at specified location strawberry
print("Specify position 2 to insert elements:","strawberry",table.insert(fruits,2,"strawberry"))
for k,v in ipairs(fruits) do
    print(k,v)
end

Code execution results:

fruits The type of is:	table
 towards fruits in insert mango: 
1	banana
2	apple
3	pear
4	orange
5	mango
 Delete the last element:	mango
1	banana
2	apple
3	pear
4	orange
 Delete the last element:	orange
1	banana
2	apple
3	pear
 Specify position 2 to insert elements:	strawberry
1	banana
2	strawberry
3	applea
4	pear

table sorting

The table sorting method is table.sort(), which is ascending by default

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 result of code execution is:

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

Lua modules and packages

Modules are similar to an encapsulation library. After Lua5.1, Lua added a standard module management mechanism that allows common code to be placed in a file and called elsewhere as an Api interface, which facilitates code reuse and reduces code coupling.

The Lua module is a table made up of known elements such as variables and functions, so creating a module is equivalent to creating a table, putting the constants and functions you need to export into the table, and returning the table.

-- File name module.lua
-- Define a name module Module
module = {}
 
-- Define a constant
module.constant = "This is a constant"
 
-- Define a function
function module.func1()
    io.write("This is a public function!\n")
end
 
local function func2()
    print("This is a private function!")
end
 
function module.func3()
    func2()
end
 
return module

The example above is to create a custom module, module.lua, in the code format of the file.From the code format of the file, the structure of the module is the structure of a table.So you can call constants or functions in a module just as you call elements in a table.

func2 is a local local variable declared inside a module and represents a private function. Therefore, it is not a private function that can be accessed directly from outside. This private function, module.func3(), can only be called through other public functions in the module.

Module Load Function

Lua provides a function to load modules: require.To load a module, simply call the function.

--Call Format
require("<Module name>")  require "<Module name>"
-- test_module.lua file
-- module Module is mentioned above module.lua
require("module")
print(module.constant)
module.func3()
--Define an alias variable for the loaded module
local m = require("module")
print(m.constant)
m.func3()

The result of code execution is:

This is a constant
 This is a private function
 This is a constant
 This is a private function

Module Loading Mechanism

For custom modules, the module file does not fit in any directory. The load function require has its own unique file path loading policy, which tries to load modules from Lua files or C libraries.

The path require uses to search for Lua files is stored in the global variable package.path, which, when Lua is started, uses the environment variable LUA_The PATH value initializes this environment variable, and if it is not found, it is initialized using a compile-time defined default path.

If there is no LUA_PATH is an environment variable that you can customize to open the.profile file in the root directory of the current user, create it if not, or open.bashrc to add the'~/lua/'path to the LUA_PATH environment variable.

#LUA_PATH
export LUA_PATH="~/lua/?.lua;;"

package.path is actually set at virtual machine startup if LUA_If PATH exists, then the environment variable is used as its value and the';'in this environment variable is used.Replace with the default value defined in luaconf.h, or use the default value defined in luaconf.h directly if it does not exist

Global variable package.path: Saves the search path for loading external modules, which is a "template-like path" that may contain alternative symbols "?".The symbol is replaced and the file is found to exist, which calls its specific interface.Assume that package.path has a value of:

/Users/dengjoe/lua/?.lua;./?.lua;/usr/local/share/lua/5.1/?.lua;/usr/local/share/lua/5.1/?/init.lua;/usr/local/lib/lua/5.1/?.lua;/usr/local/lib/lua/5.1/?/init.lua

If called in lua code: require ("module"), the template path in package.path is replaced by

/Users/dengjoe/lua/module.lua;
./module.lua
/usr/local/share/lua/5.1/module.lua
/usr/local/share/lua/5.1/module/init.lua
/usr/local/lib/lua/5.1/module.lua
/usr/local/lib/lua/5.1/module/init.lua

When the template path mentioned above is replaced, an attempt is made to open the file directory to search for the target file module.lua.Find the target file and call the module require("module").

Invoke module steps:

Check that the package.loaded table has already loaded the module and returns directly if it has already been loaded, so repeatedly loading the same module will only load once more.

If the package.loaded has no record of this module, the "template path" above replacing packag.path will occur to find the target file, call the LoadFile load after finding the target file, and return a function (loader).If the corresponding target file is not found, the dynamic library so file is searched under the path specified by package.cpath, and if found, the package.loadlib is called to load and find luaopen_modname function (that is, the result of loadfile)

Whether you are looking for the corresponding lua and so files in the package.path or package.cpath path, you now have a loader loader (function)

The require function calls the loader function and passes in two parameters (most modules ignore parameters), and any returned values are stored in the package.loaded table so that they can be returned directly the next time they load

Lua meta-table

Lua provides metatables that allow us to see the table's behavior, each associated with its corresponding meta-method.

When Lua tries to add two tables, it first checks if one of them has a meta-table, and then checks if one of them is called'_The field of add, if found, the corresponding value (often a function or table) is called as the metamethod.

Two functions that deal with meta-tables:

Setmetatable: Sets the metatable to the specified table if _exists in the metatableMetatable key value, setmetatable will fail.

getmetatable: Returns the metatable of an object

Lua Collaborator

Lua collaborators (coroutine s) are similar to threads in that they have separate stacks, independent local variables, independent instruction pointers, and share global variables and most other things with other collaborators

Differences between threads and collaborators:

The main difference is that programs with multiple threads can run several threads at the same time, and collaborators need to run in collaboration with each other.That is, only one collaborator is running at any given time, and the running collaborator is only suspended if it is explicitly required to suspend.

Collaborators are a bit like synchronous multithreads, and several threads waiting for the same thread lock are a bit like collaboration.

Basic Grammar

Methoddescribe
coroutine.create()Creates a coroutine, returns a coroutine, and the parameter is a function that wakes up the function call when used with resume
coroutine.resume()Restart coroutine for use with create
coroutine.yield()Hanging a coroutine and setting it to a pending state can be useful in combination with resume
coroutine.status()Review the status of coroutine Note: There are three states of coroutine: dead, suspended, running. Please refer to the following program for details when this happens
coroutine.wrap()Create a coroutine, return a function, once you call this function, enter the coroutine, and the create function repeats
coroutine.running()Return the running coroutine, a coroutine is a thread, and when using running, a corouting's thread number is returned

Lua File I/O

The Lua I/O library is used to read and process files.It is divided into simple mode and complete mode.

Simple mode: has a current output file and a current input file, and provides operations related to those files.

Full mode: using external file handles.It is an object-oriented form that defines all file operations as file handles

Simple mode is appropriate for doing simple file operations, but full mode is appropriate for some advanced file operations, such as reading multiple files at the same time.

--Open File Action Statement
file = io.open(filenaeme,[,mode])

File Operation Mode

Patterndescribe
rOpen the file read-only, it must exist.
wOpen a write-only file. If the file exists, the file length is zero, and the contents of the file disappear.Create a file if it does not exist.
aOpen a write-only file in an attached manner.If the file does not exist, it will be created. If the file exists, the data written will be added to the end of the file, that is, the original contents of the file will be preserved. (EOF reserved)
r+Open the file as read-write and it must exist.
w+Open a readable and writable file, and if the file exists, the file length is cleared to zero, and the contents of the file disappear.Create a file if it does not exist.
a+Similar to a, but the file is readable and writable
bBinary mode, if the file is binary, add b
+Number indicates that the file can be read or written

Simple mode

Simple mode uses standard I/O or a current input file and a current output file.

-- Open file read-only
file = io.open("test.lua", "r")

-- Set the default input file to test.lua
io.input(file)

-- First line of output file
print(io.read())

-- Close open files
io.close(file)

-- Open Write-Only Files Attached
file = io.open("test.lua", "a")

-- Set the default output file to test.lua
io.output(file)

-- Add on the last line of the file Lua Notes
io.write("--  test.lua End of file comment")

-- Close open files
io.close(file)

io.read() reads the parameter list

Patterndescribe
"*n"Read a number and return it.Example: file.read("*n")
"*a"Read the entire file from its current location.Example: file.read("*a")
"*l" (default)Read the next line and return nil at the end of the file (EOF).Example: file.read("*l")
numberReturns a string specifying the number of characters, or nil when EOF occurs.Example: file.read(5)

Full mode

Usually we need to process multiple files at the same time.Require file:function_name instead of io.function_name method.

Lua error handling

Error handling is necessary in the running of a program in any language. If you do not pay attention to error handling, information will be leaked and the program will not run.

Error Type: Syntax Error, Run Error

Syntax error

Syntax errors are usually caused by improper use of program components such as operators and expressions

Run Error

Running errors are programs that run normally but output error information

Lua Debugging

Lua provides debug libraries for creating our custom debuggers.The debug library in Lua contains debug functions.

Sequence NumberMethod & Purpose
1.**debug()πŸ˜—*Enter a user interaction mode and run each string that the user enters.With simple commands and other debugging settings, users can review global and local variables, change their values, calculate expressions, and so on.Entering a cont-only string on a line will end the function so that the caller can continue running down.
2.**getfenv(object)πŸ˜—*Returns the environment variable of the object.
3.**gethook(optional thread)πŸ˜—*Returns three values representing thread hook settings: current hook function, current hook mask, current hook count
4.**getinfo ([thread,] f [, what])πŸ˜—*Returns a table of information about a function.You can either provide the function directly or use a number f to represent the function.The number f denotes the function running at the corresponding level of the call stack of the specified thread: level 0 denotes the current function (getinfo itself);Layer 1 represents a function that calls getinfo (unless it is a tail call, which does not count in the stack);Wait.If f is a number larger than the number of active functions, getinfo returns nil.
5.**debug.getlocal ([thread,] f, local)πŸ˜—*This function returns the name and value of a local variable whose index is local at the f-level of the stack.This function is used to access not only explicitly defined local variables, but also formal parameters, temporary variables, and so on.
6.**getmetatable(value)πŸ˜—*Push the meta-table of the values that the given index points to on the stack.If the index is invalid, or if the value does not have a metatable, the function returns 0 and does not press anything on the stack.
7.**getregistry()πŸ˜—*Returns the registry, a predefined table that can be used to hold any Lua value that the C code wants to save.
8.**getupvalue (f, up)**This function returns the name and value of the value on the first up of function F.If the function does not have that upper value, return nil.Variable names beginning with'(') (open parentheses) denote unnamed variables (code blocks that remove debugging information).
10.sethook ([thread,] hook, mask [, count]): Sets a function as a hook function.The string mask and the number count determine when the hook will be called.A mask is a string composed of the following characters, each of which has its own meaning:'c': call the hook whenever Lua calls a function; 'r': Call the hook whenever Lua returns from a function;'l': Call the hook whenever Lua enters a new line.
11.**setlocal ([thread,] level, local, value)πŸ˜—*This function assigns value to the local variable of the level-on-stack function.If there is no variable, the function returns nil.If level is out of bounds, an error is thrown.
12.** setmetatable (value, table)πŸ˜—*Set the meta-table of value to table (which can be nil).Returns value.
13.** setupvalue (f, up, value)πŸ˜—*This function sets value to the top-up value of function F.If the function does not have that upper value, return nil; otherwise, return the name of the upper value.
14.**traceback ([thread,] [message [, level])πŸ˜—*If the message has one and is not a string or nil, the function returns the message directly without any processing.Otherwise, it returns stack backtrace information for the call stack.The string optional message is added at the beginning of the stack backtrace information.The numeric optional level indicates at which level of the stack to start backtracking (default is 1, where traceback is called).

Lua garbage collection

Lua uses automatic memory management.There is no need to consider how the memory of the created object is allocated or how it is freed when the object is no longer in use.

Lua runs a garbage collector to collect all dead objects (objects that are no longer accessible in Lua) to complete automatic memory management.The memory Lua uses, strings, tables, user data, functions, threads, internal structures, and so on, is managed automatically.

Lua implements an incremental tag-scan collector that uses these two numbers to control the garbage collection cycle.Garbage Collector Interval Rate and Garbage Collector Step Rate.The two numbers are in units of percentages (that is, the value is 100, which is internally expressed as 1 percent of 100).

Garbage collection intervals control how long the collector has to wait before starting a new cycle.Increasing the size decreases the motivation of the collector.When this value is less than 100, the collector will not wait until a new cycle is started.Setting this value to 200 will cause the collector to wait until its total memory usage has doubled.

The garbage collector step rate controls the rate at which the collector operates relative to the speed of memory allocation.Whether increasing this will make the collector more active or increase the length of each incremental step.Do not set the value below 100, because the collector works too slowly (the collector operates faster than the memory allocation speed), and the default value is 200, which means that the collector works at twice the memory allocation speed.

Garbage Collector Function

  • Lua provides functions to control automatic memory management:
  • collectgarbage("collect"): Make a complete garbage collection cycle.It provides a different set of functions with the parameter opt:
  • collectgarbage("count"): Returns the total amount of memory used by Lua in K bytes.This value has a decimal part, so you only need to multiply 1024 to get the exact number of bytes Lua uses (unless it overflows).
  • collectgarbage("restart"): Restart the automatic operation of the garbage collector.
  • collectgarbage("setpause"): Set arg as the interval rate of the collector.Returns the previous value of the interval rate.
  • collectgarbage("setstepmul"): Returns the previous value of the step rate.
  • collectgarbage("step"): Run the garbage collector in one step.Step size is controlled by arg.When 0 is passed in, the collector steps (indivisible) one step.Incoming a non-zero value, the collector collects work equivalent to Lua allocating these large (K bytes) of memory.true is returned if the collector ends a loop.
  • collectgarbage("stop"): Stops the garbage collector from running.The collector will only run for explicit calls until the call is restarted.

Lua Object Oriented

The most basic structure in Lua is a table, which can be used to represent the properties of an object.Functions in Lua can be used to represent methods in objects.Classes in Lua can be simulated using table+function.

| ** setlocal ([thread,] level, local, value)πŸ˜—*This function assigns value to the local variable of the level-on-stack function.If there is no variable, the function returns nil.If level is out of bounds, throw an error. |
| 12. | **setmetatable (value, table)πŸ˜—*Set the meta-table of value to table (which can be nil).Return value. |
| 13. | **setupvalue (f, up, value)πŸ˜—*This function sets value to the top-up value of function F.If the function does not have that upper value, return nil; otherwise, return the name of the upper value. |
| 14. | ** traceback ([thread,] [message[, level])πŸ˜—*If the message has one and is not a string or nil, the function returns the message directly without any processing.Otherwise, it returns stack backtrace information for the call stack.The string optional message is added at the beginning of the stack backtrace information.The number optional level indicates at which level of the stack to start backtracking (default is 1, where traceback is called). |

Lua garbage collection

Lua uses automatic memory management.There is no need to consider how the memory of the created object is allocated or how it is freed when the object is no longer in use.

Lua runs a garbage collector to collect all dead objects (objects that are no longer accessible in Lua) to complete automatic memory management.The memory Lua uses, strings, tables, user data, functions, threads, internal structures, and so on, is managed automatically.

Lua implements an incremental tag-scan collector that uses these two numbers to control the garbage collection cycle.Garbage Collector Interval Rate and Garbage Collector Step Rate.The two numbers are in units of percentages (that is, the value is 100, which is internally expressed as 1 percent of 100).

Garbage collection intervals control how long the collector has to wait before starting a new cycle.Increasing the size decreases the motivation of the collector.When this value is less than 100, the collector will not wait until a new cycle is started.Setting this value to 200 will cause the collector to wait until its total memory usage has doubled.

The garbage collector step rate controls the rate at which the collector operates relative to the speed of memory allocation.Whether increasing this will make the collector more active or increase the length of each incremental step.Do not set the value below 100, because the collector works too slowly (the collector operates faster than the memory allocation speed), and the default value is 200, which means that the collector works at twice the memory allocation speed.

Garbage Collector Function

  • Lua provides functions to control automatic memory management:
  • collectgarbage("collect"): Make a complete garbage collection cycle.It provides a different set of functions with the parameter opt:
  • collectgarbage("count"): Returns the total amount of memory used by Lua in K bytes.This value has a decimal part, so you only need to multiply 1024 to get the exact number of bytes Lua uses (unless it overflows).
  • collectgarbage("restart"): Restart the automatic operation of the garbage collector.
  • collectgarbage("setpause"): Set arg as the interval rate of the collector.Returns the previous value of the interval rate.
  • collectgarbage("setstepmul"): Returns the previous value of the step rate.
  • collectgarbage("step"): Run the garbage collector in one step.Step size is controlled by arg.When 0 is passed in, the collector steps (indivisible) one step.Incoming a non-zero value, the collector collects work equivalent to Lua allocating these large (K bytes) of memory.true is returned if the collector ends a loop.
  • collectgarbage("stop"): Stops the garbage collector from running.The collector will only run for explicit calls until the call is restarted.

Lua Object Oriented

The most basic structure in Lua is a table, which can be used to represent the properties of an object.Functions in Lua can be used to represent methods in objects.Classes in Lua can be simulated using table+function.

Posted by hoogeebear on Tue, 07 Sep 2021 09:25:26 -0700