lua study notes

Posted by KrisCons on Mon, 07 Mar 2022 20:09:04 +0100

brief introduction

Lua is a lightweight and compact script language, which is written in standard C language and open in the form of source code. Its design purpose is to be embedded in the application, so as to provide flexible expansion and customization functions for the application.

Lua was developed in 1993 by a research team at the Pontifical Catholic University of Rio de Janeiro, Brazil

Design purpose

In order to embed in the application, so as to provide flexible expansion and customization functions for the application.

lua characteristics

  • Lightweight: it is written in standard C language and open in the form of source code. After compilation, it is only more than 100 K, which can be easily embedded in other programs.
  • Extensibility: Lua provides very easy-to-use extension interfaces and mechanisms: these functions are provided by the host language (usually C or C + +), and Lua can use them as if they were built-in functions.
  • Other features
    • Support process oriented programming and functional programming;
    • Automatic memory management; Only a general type of table is provided, which can be used to realize arrays, hash tables, sets and objects;
    • Language built-in pattern matching; Closure; Function can also be regarded as a value; Provide multithreading (collaborative process, not the thread supported by the operating system);
    • Closure and table can easily support some key mechanisms required by object-oriented programming, such as data abstraction, virtual function, inheritance and overloading.

Application scenario

  • Game development
  • Stand alone application script
  • Web application script
  • Extensions and database plug-ins such as MySQL Proxy and MySQL WorkBench
  • Security system, such as intrusion detection system

Basic grammar

output

print("content")

notes

– single line comment - [[multiline comment]] –

keyword

andordoifelseelseif
breakendforthenwhilelocal
returnrepeatfalsetrueinnot
nilfunctionuntilgoto

data type

nil

boolean

number

function

table

userdata

thread

data typedescribe
nilNull type, indicating an invalid value, which is false in the conditional expression
booleanFalse and true, only nil and false in the expression make the condition false, and others are true, including (0)
numberDouble type real floating point number
stringString type, represented by a pair of double or single quotation marks
functionFunctions written by c or lua
tableA table (associative array) whose members can be numbers, strings, or table types. Construct expression by {}
userdataCustom type, which represents any c data structure stored in variables
threadThread, execute cooperative program

lua variable

global variable

All variables in Lua are global variables, even in statement blocks or functions, unless explicitly declared as local variables with local.

a=10

local variable

The scope of a local variable is from the declaration position to the end of the statement block (code block).

Code block: control structure, function body, chunk (file or string of variable declaration)

Benefits of local variables

1. Avoid name conflicts

2. Fast access

locat a=10

Field in table

Simultaneous assignment of multiple variables

Lua can assign values to multiple variables at the same time. The elements of the variable list and value list are separated by commas. The values on the right of the assignment statement will be assigned to the variables on the left in turn.

a, b = 10, 2*x       <-->       a=10; b=2*x

Forced type conversion

//string to number
print(tonumber("10"+10))  //20
//number to string
print(tostring(13).."25")  //1325

operator

Arithmetic operator

Can only operate between numbers

Binary operator

Between two numbers (+,, *, /, ^)

print (a+b)
Unary operator

A negative number (-)

print(-10)

Relational operator

(==,~=,> , >= , < . <= )

The return value of the relational operator is a boolean value (false/true)

UserData, table and function can be compared only if the pointing object is the same Yes (= =)

Logical operator

The result of the and,or operation is related to the operand

print(1 and 100) //Take the greater of 100
print(1 or 100)	//one 	    Take the small value
print(true or false) //false
print(true or false) //true

concatenation operator

(...) concatenates a number string

Digital connection

print(12 .. 24) //1224

String connection

print("love".."you") //loveyou

priority

^Power

not, - no, negative

*, / multiplication and division

+, - addition and subtraction

... connect

==, ~ =, >, > =, <, < = relationship

And logic and

Or logical or

Table initialization

a={}
a={x=100,y=200}
print(a.x,a.y)

Basic grammar

Assignment exchange

a=100
b=200
a,b=b,a  //a=200,b=100

Control structure statement

if

if conditions then
	then-part
end
if conditions then
	then-part
else
	else-part
end
if conditions then
	then-part
else if conditions then
	then-part
......
else else-part
end
a=1
b=2
if a>b then
	print("a>b")
else if a<b then
	print("a<b")
else print("a=b")
end
end				//a=b

while

Precondition judgment, recycling

while conditions do
	statement
end
b=10
while b<20 do
print(b)
b=b+1
end		//10 11 12 13 14 15 16 17 18 19

repeat-until

First cycle, then condition judgment

repeat
	statement
until conditions
b=10
repeat
print(b)
b=b+1
until b>20  //10 11 12 13 14 15 16 17 18 19 20

for numeric loop

for var=exp1,exp2,exp3 do //(start value, end value, increase value each time) / / exp defaults to 1 when not writing
	statement
end
for i=1,21,2 do
print(i)
end  //1 3 5 7 9 11 13 15 17 19 21
for i=10,0,-1 do
print(i)
end	//10 9 8 7 6 5 4 3 2 1 0

for generic loop

pairs iterator (full traversal) can retrieve all data types in the table, but the retrieval order cannot be guaranteed. ipairs can only retrieve arrays

for k,v in ipairs(t) do//(data number in table k, data content in table v, and table name in table t)
end
t1={"l","o","v","e"} //"," shall be added between different data in the table
for k,v in ipairs(t1) do
print(v)
end

break

Exit loop

for i=1,100,2 do
if i==21 then break
else print(i) end
end         //1 3 5 7 9 11 13 15 17 19 21

return

Function return value

function add(a,b)
return a+b
end
print(add(100,200))

function

definition

//1,
function func_name(argument-list) //(function name parameter list)
	statement-list  //sentence
end
//2,
func_name=function(argment-list)
	statement-list
end
//3. Functions defined in table
tab={}
tab.func_name=function(argument-list)
	statement-list
end
//4,
tab={}
tab={func_name=funcation(argument-list)
	statement-list
end}
//5,
tab={}
function tab.func_name(argument-list)
	statement-list
end
//1
function add(a,b)
return a+b
end
//2
add=function(a,b)
return a+b
end
//3
tab={}
tab.add=function(a,b)
return a+b
end
//4
tab={}
tab={add=function(a,b)
return a+b
end}
//5. Commonly used
tab={}
function tab.add(a,b)
return a+b
end
//Variable parameters
tab={}
function tab.sum(...) //The number of parameters is not specified
	local s=0
for k,v in ipairs(arg) do  //arg number of parameters not specified
	s=s+v
end
	return s
end
print(tab.num(1,2,3,4,5))

closure

A function is defined inside another function

"Closure", which lua interprets as a closure, has this feature: if a function is written in another function, the internal function can access the local variables in the external function. This feature is called lexical domain.

function out_func(argument-list)
	local var;
	return function(argument-list)
	end
end  
function newCounter()
	local i=0
	return function() //Internal function
		i=i+1		//Local variables using external functions
		return i
	end
end

c1=newCounter()
print(c1())	//1
print(c1())	//2
print(c1()) //3

function call

1. General call method function (argument list)

2. Parentheses () can be omitted when there is only one parameter (string or table)

3,tab:func_name(argument)->tab.func_namee(tab,argment)

4. Call of closure

5. The number of arguments and formal parameters of the calling function is different

6. Tail call (the last action of a function is to call another function)

//Commonly used
function(argument-list)
add(a,b)
//Call in table
table_name,function_name(argument-list)
tab.add(1,2)
//Tail call
function aa()
	return 1
end
function bb()
 	a=a+1
 	b=b+1
 	return aa()+1
end
//Table as function parameter
function sum(tab)
	local sum=0
	for k,v in ipairs(tab) do
		sum=sum+v;
	end
	return sum
end
function mul(tab)
 	local sum=1
 	for k,v in ipairs(tab) do
 	sum=sum*v
 	end
 	return sum
end
tab={1,2,3,4}
print(sum(tab))
print(mul(tab))

Iterators and generics

Synergetic process

process

An instance of a running program

thread

A relatively independent and schedulable execution unit in the process is the basic unit for the system to independently schedule and dispatch cpu, and the scheduling unit of running programs

Synergetic process

Cooperative programs complete a given task through cooperation (function call), and there is only one instruction executing at the same time

coroutine.create() //Collaborative process creation
coroutine.yield()	//Co process pause
coroutine.resume()	//Operation coordination process
coroutine.status()	//View Collaboration Status
//Operation coordination process
function f()
print("hello")
end
co=coroutine.create(f)
coroutine.resume(co)
//   hello
//Complete collaborative process
function f1()
	while true do
	local res,v1,v2=coroutine.resume(c2,100,300)
	print(v1,v2)
	end
end
c1=coroutine.create(f1)
function f2()
	while true do
	local v1,v2=coroutine.yield(1,3)
	print(v1,v2)
	end
end
c2=coroutine.create(f2)
coroutine.resume(c1)  //100 300 1 3 repeat printing

data structure

lua only has the data structure of table. Arrays, linked lists and queues need to be extended from table

array

The elements accessed through subscripts in lua can implement arrays

One bit array

t={1,2,3,4}  //T [1], t [2], t [3] Lua array starts from 1
print(t[1])  // 1

Two dimensional array

t={{1,2},{3,4},{5,6}}
print(t[2][1]) //3

Linked list

t={1,2,3,4}
n=table.getn(t)
list=null
for i=1,n do
	list={val=t[i],next=list}
end
print(list.val,list.next.val,list.next.next.val,list.next.next.next.val)
//Define iteration function
function ipairs_iter(t,node)
	if node==nil then return t
	else return node.next
	
//Initialization function
function ipairs_list(t)
	return lpairs_iter,t,nil  //Return iteration function
//Traversal linked list
for node in ipairs_list(list) do
	print(node.val)
end
//Delete node
function delnode(val)
	for node inpairs_list(list) do
	if node.next~=nil and node.next.val==val then
	local p=node.next
	node.next=p.next
	p.next=nil
	end
end
end
delnode(list,3);

queue

Meta table

(function) implement the arithmetic operation (addition) of two tables (_add)

//Meta table addition
a={1,2,3}
b={1,2,3}
mt={}
mt.__add=function(a,b) //Define meta table
	local len=table.getn(a)
	local res={}
	for i=1,len do
		res[i]=a[i]+b[i]
	end
	return res
end
setmetatable(a,mt) //Set meta table
setmetatable(b,mt)
c=a+b
for k,v in ipairs(c) do
	print(v)
end        // 2 4 6
//Meta table connection
a={1,2,3}
b={1,2,3}
mt={}
mt.__concat=function(a,b)
	local len=table.getn(a)
	local res={}
	for i=1,len do
		res[i]=a[i]..b[i]
	end
	return res
end
setmetatable(a,mt)
setmetatable(b,mt)
c=a..b
for k,v in ipairs(c) do
	print(v)
end        // 11 22 33

Package

//foo.lua package
local class={}
function class.foo(a,b)
	return a+b
end
return class
//Call the package require function to find the file
local c=require("foo")
print(c.foo(1,2))

System library

// table.insert(t,i) t table name
local t={}
for i=1,10 do
	table.insert(t,i)
end

for k,v in ipairs(t) do
	print(k,v)
end
//All kinds of functions in table start with table name 1
table.setn    
table.insert(t,1)  
table.getn(t) //Length of calculation table t    
table.foreachi    
table.maxn    //Get maximum index value
table.foreach 
table.concat  
table.sort    
table.remove(t,2) //Delete the 2 value in table t
//Custom string format
string.format("hello%d",2)
print(string.format("hello %d",2))

Object oriented feature implementation

Realize object-oriented features, classes and inheritance by copying tables

--Copy function
function clone(tab)
	local ins={}
	for k,v in pairs(tab) do
		ins[key]=v
	end
	return ins
end

function copy(dist,tab)
	for k,v in pairs(tab) do
		dist[key]=v
	end
end

people={}
people.say=function(self)
print("people say hi"..self.name)
end

people.new=function(name)
	local self=clone(people)
	self.name=name
	return self
end
--copy people Class create class instance
local p=people.new("ZhangSan")
p.say(p)
--p:say(p)

man={}
man.new=function(name)
	local self=people.new(name)
	copy(self,man)
	return self
end

Topics: lua