Simple use of Lua, and some simple data types

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

There is no operation of auto-increment ++ and auto-decrement -- in Lua. It can only be done through variable = variable + variable (for example: a=a+b).

Lua concatenation character: ".." instead of "+"

Lua's and, or, non: and, or, ~

Lua's nil type cannot be connected to any data type, but it can be output separately (an error will be reported)

a=1,

b=nil,
print(a..b) --will report an error, nil cannot be connected with other types.
Print(a) --a=1
print(b) --b=nil can only be output alone

Ternary operator: b=1>2?1:0. In Lua b= (x>y) and x or y

x,y=1,2
sum = (x>y) and x or y
print(sum)

Output 2

Everything in Lua can be a variable. There is no declaration of variables, only assignment of variables.

Get the length of a string

#a Get the length of a string

For multiple definitions of variables, the extra parts will not be output or replaced, and no errors will be reported for multiple definitions.

Example: a,b=1,2,3,

print(a..b) --output a..b=12, which means a=1, b=2, 3 is a useless number and no error will be reported

Judgment statements if, elseif, else

1. if condition then method body end

2、

if condition then

        method body

elseif condition then

        method body

else

        method body

 end

a,b=1,2
if a<b then
    print('a<b')
end

if a<b then
print('a<b')
else
print('a>=b')
end

if a<b then
    print('a<b')
elseif a==b then
    print('a==b')
else
    print('a>b')
end

if not(a>b) then
print('a<b')
end 

Loop statement for condition (variable = min, max, auto-increment number) do...end, while condition do...end, repeat...until condition 

while condition do...end

a,sum=1,0
while a<=10 do
sum=sum+a;
a=a+1
print(sum)
end

Output: 1, 3, 6, 10, 15, 21, 28, 36, 45, 55

 repeat...until condition 

a,sum=1,0
repeat 
    sum=sum+a;
a=a+1
print(sum)
until a>10

Output: 1, 3, 6, 10, 15, 21, 28, 36, 45, 55

sum=0
for a=1,10,1 do
    sum=sum+a
    print(sum)
end

Output: 1, 3, 6, 10, 15, 21, 28, 36, 45, 55

sum=0
for a=1,-5,-1 do
    sum=sum+a
    print(sum)
end

 Output: 1, 1, 0, -2, -5, -9, -14

 The use and definition of Lua functions (methods)

function Add()
a=1
b=3
c=b-a
print(c)
end

Output: 2

function Sub(a,b)
c=a+b
print(c)
Add()
end

Output: 3, 2

function Div(a,b)
    c=a+b
    return c
end
x=Div(1,2)
print(x)

Output: 3 

 function Mu()
    a=1
    b=3
    c=a+b
    return c
end
y=Mu()
print(y)

Output: 4

 The use of multiple parameters #a represents a large series of numbers

function Sum(...)
    a={...}
    b=1;
    for    i=1,#a do
        b=b*a[i]
        print(b)
    end
end
Sum(1,2,3,4,5,6)

Output: 1, 2, 6, 24, 120, 720

 Nesting of functions:

function Get()
    su = function()
        print("hhhh")
    end
    return su
end
getsu=Get()
getsu()

Output: hhhh

function Get1()
    return function()
        print("Let us work together for love")
    end
end

getNext=Get1()
getNext()

 Output: Let us work together for love

Lua does not support overloading. Using the same method will overwrite it.

function Add()
a=1
b=2
c=a+b
print(c)
end        --3

function Add(a,b)
c=a+b
print(c)
end

Add(2,3)

 Output: 5; Add() function is overridden and used by Add(a,b)

 Use of math function library

i=153.4
print(math.ceil(i)) --154, math.ceil() rounds up
print(math.floor()) --153, math.floor() rounds down

print(math.abs(-12)) --take the absolute value

print(math.max(3,5,7,9,2,1)) --take the maximum value
print(math.min(3,5,7,9,2,1)) --take the minimum value

print(math.pow(2,3)) --power, 2^3
print(math.sqrt(9)) --square root

print(math.deg(math.pi)) --turn in radians
print(math.cos(math.pi)) --turn in radians
print(math.sin(math.pi)) --turn in radians
print(math. tan(math.pi)) --turn in radians

print(math.modf(1.2)) --Separate integers and decimals

Closure

--Closure example 1
function Get()
    local a =10
    return function()
        print(a)
        a=a+1
    end
end
F=Get()
F()
output: 10

--闭包例题2
function Get1(n)
    local function Get2()
        print(n)
        
    end
    local function Get3()
        n=n+10
    end
    return  Get2,Get3
end
G1,G2=Get1(2022)
G1()                --2022

G2() --2022+10 (operation)
G1() --2032 (output function)

--Closure iterator effect
function Get(t)
    local a=0
    return function()
        a=a+1
        return t[a]
    end
end
t={1,2,3,4}
F=Get(t)
print (F())
print(F())
print(F())
print(F()) 

Output: (one output and one display)

1

2

3

4

 Use of random numbers:

math.randomseed(os.time()) --Set the seed
math.random(100)
print(math.random(100)) --Random number

Output: random output

If the number type is converted to string type + number type, it will be automatically converted to number type.

The defined value is a numeric type and is also converted to a numeric type

b=12, tostring(b) is converted to string type
print(tostring(b)+2) --15
print('12'+2) --15
print(tostring(b)..2) --123

Use of strings

a='abcdb'
print(string.upper(a)) --uppercase
print(string.lower(a)) --lowercase
print(string.reverse(a)) --reverse output

print(string.find(a,'bcd')) --Find 2 4, 2 is the position of the first character found, 4 is the position of the last character print(string.sub(
a,2,3) ) --Intercept the 3rd and 4th characters in a string

print(string.rep(a,2)) --repeat 2 times
print(string.gsub(a,'b','!')) --replace a!cd! 2, 2 represents the number of substitutions

Use of table:

--Table: The subscript starts from 1, and the subscript out-of-bounds value is nil.

a={1,2,3,'A','b',true}
print(a[-1])
print(a[1]) --The value of the first subscript
print(#a) --Table The length of
print(table.getn(a)) --the length of the table

for i=1,#a,1 do --sequential output
    print(a[i])
end

for i=#a,1,-1 do --flashback output
    print(a[i])
end

Custom index

1、

b={[0]=1,2,3,'a',[-1]='b',true}
for    i=-1,#b,1 do
    print(b[i])        --b,1,2,3,a,true
end
print("\n")         --换行

2、

b={[1]=1,2,3,'a',[2]='b',true}
for    i=1,#b,1 do
    print(b[i])     --2,3,a,true
end

Lua modules (instances) are also classes in C#

--Student class
Student={     id=1001, --Attribute     name='Xiaotian', -- --Attribute     Eat=function() --Method definition in the class         print(Student.name..'It’s so delicious. eat')     end,     Study=function()         print('good good day')     end,         Fly=function(t) --method with parameters         print(t.name..'can fly')     end }











--Call access class methods and class attributes
print(Student.id..'\t'..Student.name)
Student.Eat()
Student.Study()


--Call the method
Student.Fly(Student) with parameters --The method is equivalent to the following method
Student:Fly()

--Add attributes and methods outside the class --Add
method 1:
Student.sex='Male' --Attribute
Student.Sleep=function() --Method
    print('sleep like a pig's head')
end
--Add method 2 :
function Student.Play()
    print('Have fun')
end

--Access external added attributes and methods
print(Student.sex)
Student.Sleep()
Student.Play()

Cross-file calling (calling properties of other Lua files)

require('Three') --Request the contents of other Lua files Three, local variables
    print(a)
    print(b) cannot be called

 Access module (class)

 require('Four')        
Four.Play()
Four.Sleep()

Read files, write files

    --Read, a+ can be read and written, a
file=io.open('D:\\Lua\\One\\aa.txt','r')
io.input(file)
f=io.read( )
print(f)
f=io.read()
print(f)

for i in io.lines('D:\\Lua\\One\\aa.txt') do
    print(i)
end
io.close()

--Write text (overwrite)
file=io.open("D:\\Lua\\One\\aa.txt",'w')
io.output(file)
io.write('11111')
io.close ()

--Write text (append)
file=io.open("D:\\Lua\\One\\aa.txt",'a+')
io.output(file)
--io.write('\n2222')

io.write('333')
io.close()

--Write text (append)
file=io.open("D:\\Lua\\One\\aa.txt",'a+')
io.output(file)
--io.write('\n2222')

io.write('333')
io.close()

 Iterator: pairs,ipairs are read by iterator through for loop

--自定义索引
a={[0]=11,22,33,44,55}
for f,v in pairs(a) do
    print(f,v)
end
print('88888888')
for f,v in ipairs(a) do
    print(f,v)
end

dictionary:

a={['id']=1001,['name']='李思',['age']=18} --Read the dictionary
, f is the key, v is the value
for f,v in pairs( a) do
    print(f,v) -- id 1001, name Li Si, age 18
end
print('************')        
for _,v in pairs(a) do
    print(_,v ) --id 1001, name Li Si, age 18
end
--ipairs cannot read dictionary content
for f,v in ipairs(a) do
    print(f,v) --id, name, age reading key cannot read value
end
--Single output keys
for f,v in pairs(a) do
    print(f) --id, name, age 
end    
--Single output values
​​for f,v in pairs(a) do
    print(v) --1001 , John Doe, 18
end    

 a={11,22,nil,33,44,55}
--pairs will continue to traverse when it encounters nil, and nil will not be displayed
for f,v in pairs(a) do
    print(f,v)
end

Output:

1    11
2    22
4    33
5    44
6    55


--ipairs will stop traversing when it encounters nil
for f,v in ipairs(a) do
    print(f,v)
end

Output:

1    11
2    22

 

Guess you like

Origin blog.csdn.net/m0_71624363/article/details/129893283