当前位置:网站首页>Lua-- use of data types, variables, loops, functions and operators

Lua-- use of data types, variables, loops, functions and operators

2022-06-22 22:33:00 aruba

lua It's a lightweight scripting language , from c Language writing , Design lua My original intention is to : Embedded in the application , Provide flexible expansion and customization functions lua Official website :https://www.lua.org/ You can download and install lua

One 、 first lua Program

lua There are two ways to program : Interactive and scripted . Scripted is to write a script file and execute it , Interactive is to enter lua The console is programmed , Interactive is not used in actual development , The following will be programmed using scripting

1. Create script file

lua The script does not require a suffix , But generally we all take lua For the suffix , To differentiate

vi hello.lua

The content is :

print("hello world")

2. perform lua Script

lua Script execution , Use lua command

lua ./hello.lua  

result :

Two 、 data type

Before using data types , So let's see lua Notes

lua Middle single line comments use :

--  Single-line comments 

Multiline comments use :

--[[
 Multiline comment 
]]--

Here is lua Use of data types

1. number

number Type is used to represent lua The number type in , Including integers and floating-point numbers , The precision is double

i = 1
print(i)

i = 9.99999
print(i)

print(type(i))

Running results :

2. nil

and Java Medium null similar ,nil Represents an invalid value , You can also leave a variable blank

i = 1
print(i)

i = nil
print(i)

Running results :

3. string

3.1 Define the way

There are three ways to define string types :

Define the way

describe

Single quotation marks :' Content '

Represents a single line string

Double quotes :" Content "

Same as single quotation marks

square brackets :[[ Content ]]

Represents a multiline string

s = "abc"
print(s)

s = 'def'
print(s)

s = [[
gh,
 Multi line content ,
123
]]
print(s)

Running results :

3.2 Get string length

Use # Get string length

print("-----")
s = 'abcedf'
print(#s)

Running results :

3.3 String usage +

lua Use... In a string + Time of signal , Convert string to number first

print("-----")
print('1' + 2)
print('1' + '2')

Running results :

3.4 String splicing

So how to splice strings ? Use .. Connection string

print("-----")
print("1".."2".."abc")

Running results :

4. table

table It can be used as a hash table , It can also be used as a list 、 Array .tab Is more like map

Definition table Use :{}

4.1 table Use as an array
tb = {'a','b','c'}

--  Traverse the output 
for k,v in pairs(tb) do
        print(k..":"..v)
end

Running results :

You can see ,table If you don't specify key, The default from the 1 Start indexing as key

4.2 table As map Use
tb = {k1 = '1',k2 = '2',k3 = '3'}
for k,v in pairs(tb) do
        print(k..":"..v)
end

Running results :

4.3 obtain table The elements in

Two ways :

Access method

Example

adopt table['key'], If it's an array, you don't need quotation marks

tb["k1"]

adopt table.key, If it is an array, it does not support

tb.k1

test :

tb = {k1 = '1',k2 = '2',k3 = '3'}

print(tb['k1'])
print(tb.k2)

Running results :

4.4 Modify and add table Elements

Use obtain table The way the elements in the Modification and addition can be realized by assigning values table Elements

tb = {k1 = '1',k2 = '2',k3 = '3'}

tb["k1"] = 4
tb['k4'] = 8
tb.k5 = 10


for k,v in pairs(tb) do
        print(k..":"..v)
end

Running results :

4.5 Delete table Elements

Assign an element to nil that will do

tb.k2 = nil

5. function

There are two ways to define function types :

  • Defined function , Assign a function method name to a variable
  • Anonymous functions , Directly assign a function to a variable
5.1 How to define functions
--  Define a function 
function sum(a,b)
        return a + b
end

--  Assign a function to a variable 
f1 = sum
print(f1(1,6))

Running results :

5.2 Anonymous functions
function sumAndPrint(a,b,printFunc)
        ret = a + b
        --  Call the incoming function 
        printFunc(ret)
        return ret
end

--  The third argument is a function 
sumAndPrint(10,20,
        function(result)
                print(result)
        end
)

Running results :

3、 ... and 、 Variable

1. Scope

lua Variables in are divided into local variables and global variables , Default to global variable , Local variables use local Keyword declaration

function scope()
        a = 0
        local b = 1
end

scope()
print(a)
print(b)

Running results :

2. Multivariable assignment

except 1:1( One variable corresponds to one assignment ) Perform variable assignment ,lua And support n:n 、(m < n):n、n:(m < n) Variable assignment

The way

describe

n : n

Assign values to variables in order

(m < n) : n

Assign values to variables in order , Extra values are discarded

n : (m < n)

Assign values to variables in order , Low value , The assignment is nil

a1,b1 = 1,2
print('a1:'..a1..',b1:'..b1)

a1,b1 = 5,3,4
print('a1:'..a1..',b1:'..b1)

a1,b1 = 9
print('a1:'..a1)
print(b1)

Running results :

Four 、 loop

1. while

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

Running results :

2. for

for The syntax of loops has slightly different advantages , The first value represents the initial value , The second value represents the value at the end of the condition , The third value represents the step size , Step size can be omitted without writing , The default is 1

for i = 0,10,2 do
        print(i)
end

Running results :

3. repeat until

repeat repeat After the code , Until you meet until Conditions

j = 0
repeat  
        j = j+1
        print(j)
until(j > 4)

Running results :

5、 ... and 、 Condition and jump out of loop

1. if

if Judge to execute some code that meets the conditions

n = nil
if(n == nil) then
        print('n It's empty ')
end

Running results :

2. break

break Used to force a loop out

k = 0
while(k < 10) do
        k = k+1
        if(k == 5) then
                break;
        end
        print(k)
end

Running results :

6、 ... and 、 function

From the above data types, we know , Function can also be used as a variable , Define function use function keyword , Functions are divided into named functions and anonymous functions , Named functions can be called by function names , Anonymous functions can only be called through the assigned functional variables , In addition to the above use , The function also contains the following

1. Multiple value return

lua Function can return multiple values

--  The parameter a,b,a+b Return as return value 
function moreReturn(a,b)
        return a,b,a+b
end

i,j,k = moreReturn(1,2)

print(i)
print(j)
print(k)

Running results :

2. Variable parameters

Use ... Passing variable parameters

--  Add all the parameters 
function sum(...)
        local sum = 0
        for k,v in pairs({...}) do
                sum = sum + v
        end
        return sum
end

print(sum(1,2,3,4,5))

Running results :

2.1 With fixed parameters

There are both fixed and variable parameters , Fixed parameters are written in the front

--  Format output 
function fmtPrint(fmt,...)
        io.write(string.format(fmt,...))
end

fmtPrint("%d,%s,%d\n",12,'asd',66)

Running results :

2.2 select function

lua in select Function can handle variable parameters , For example, obtain variable parameter length , Intercept variable parameters

-- averaging 
function avg(...)
        local avg = 0
        for k,v in pairs({...}) do
                avg = avg + v
        end

        return avg / select("#",...)
        --return avg / #{...}
end

print(avg(2,4,6,8))

Running results :

--  Intercept variable parameters 
function limit(limit,...)
        return select(limit,...)
end


a,b,c = limit(2,"a","b","c","d","e")
print(a)
print(b)
print(c)

Running results :

7、 ... and 、 Operator

Operators are common , Some we have used before

1. Arithmetic operator

Symbol

describe

+

Add

-

reduce

*

ride

/

except

%

Remainder

^

Power

-

Minus sign

2. Relational operator

Symbol

describe

==

be equal to

~=

It's not equal to

>

Greater than

<

Less than

>=

Greater than or equal to

<=

Less than or equal to

3. Logical operators

Symbol

describe

and

also

or

perhaps

not

Not

4. Other operators

Symbol

describe

..

String connector

#

Length calculator

原网站

版权声明
本文为[aruba]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/173/202206221823301552.html