Lua language quick start

1. Lua Quick Start

1.1 Data type

There are not many data types in Lua, you can use the type function to return the type of a value

print(type(print))
print(type(true))
print(type(360.0))
print(type({
    
    }))
print(type(nil))
--function
--boolean
--number
--table
--nil

1.1.2 String

In Lua, a string is an immutable value. If you want to modify a string, it is equivalent to creating a new string. This approach is obviously pros and cons: the advantage is that even if the same string appears many times, there is only one copy in the memory; but the disadvantage is also obvious. If you want to modify and splice strings, you will create a lot of unnecessary extras. String.

The following piece of code illustrates this drawback. Concatenate the numbers from 1 to 10 as strings. In Lua, two dots are used to represent the addition of strings

local s = ""
for i = 1, 10 do
    s = s .. tostring(i)
end print(s)

I have looped 10 times here, but only the last time is what I want, and the 9 newly created strings in the middle are all useless. They not only take up extra space, but also consume unnecessary CPU operations.

In addition, in Lua, there are three ways to express a string: single quotes, double quotes, and long brackets ([[]]).
The string in the long brackets will not be escaped. If the string contains the long bracket itself, add one or more = signs in the middle of the long bracket

print([[string has \n and \r]])
-- string has \n and \r
print([=[string has a [[]].]=])
-- string has a [[]].

1.1.3 Boolean

In Lua, only nil and false are false, others are true, including 0 and empty strings are also true.

local a = 0
if a then
    print("true")
end
a = ""
if a then
    print("true")
end

This judgment method is inconsistent with many common development languages. Therefore, in order to avoid making mistakes on this kind of problem, you can explicitly write the comparison object, such as the following:

local a = 0
if a == false then
    print("true")
end

1.1.4 Numbers

Lua's number type is implemented with double-precision floating-point numbers. It is worth mentioning that LuaJIT supports dual-number (dual number) mode, that is to say, LuaJIT will use integers to store integers according to the context, and use double-precision floating-point numbers to store floating-point numbers.

In addition, LuaJIT also supports large integers with long integers, such as the following example
resty (OpenResty command)


$ resty -e 'print(9223372036854775807LL - 1)'
9223372036854775806LL

1.1.5 Functions

The function can be stored in a variable, or can be used as the input and output parameters of another function. For
example, the following two function declarations are completely equivalent:

function foo()
 end

with

foo = function ()
 end

1.1.6 table

Table is the only data structure in Lua

local color = {
    
     first = "red" }
print(color["first"])
--red

1.1.7 Null value

In Lua, a null value is nil. If a variable is defined but no value is assigned, its default value is nil:

local a
print(type(a))
--nil

1.2 Commonly used standard libraries

Lua is relatively small and does not have many built-in standard libraries

1.2.1 string library

String manipulation is the most commonly used, and it is also the place with the most pits. Lua's regularity is unique and does not comply with PCRE's specifications.

Among them, string.byte(s [, i [, j ]]) is a commonly used string library function, which returns the characters s[i], s[i + 1], s[i + 2], ·· ····, ASCII code corresponding to s[j]. The default value of i is 1, which is the first byte, and the default value of j is i.

print(string.byte("abc", 1, 3))
print(string.byte("abc", 3)) -- 缺少第三个参数,第三个参数默认与第二个相同,此时为 3
print(string.byte("abc"))    -- 缺少第二个和第三个参数,此时这两个参数都默认为 1
--97 98 99
--99
--97

1.2.2 table library

table.concat is generally used in string splicing scenarios, such as the following example. It can avoid generating a lot of useless strings.

local a = {
    
    "A", "b", "C"}
print(table.concat(a))

1.2.3 math library

The Lua math library consists of a set of standard mathematical functions. The introduction of the math library not only enriches the functions of the Lua programming language, but also facilitates the writing of programs.

For example, the following code can generate two numbers randomly within a specified range.

math.randomseed(os.time())
print(math.random())
print(math.random(100))

1.3 Dummy variables

Lua provides the concept of a dummy variable, named after an underscore, to indicate that it discards unnecessary values ​​and only serves as a placeholder.

Let's take the standard library function string.find as an example to see the usage of dummy variables. This standard library function returns two values, representing the start and end subscripts.

If you only need to get the starting subscript, then it is very simple, just declare a variable to receive the return value of string.find:

local start = string.find("hello", "he") 
print(start)
--1

But if you only want to get the ending index, you must use dummy variables:

local _, end_pos = string.find("hello", "he")
print(end_pos)
--2

In addition to being used in the return value, dummy variables are often used in loops, such as the following example:

for _, v in ipairs({
    
     4, 5, 6 }) do
    print(v)
end
--4
--5
--6

2. The special features of Lua language

2.1 Lua's subscripts start from 1

t={
    
    100};
print(type(t[0]))
print(type(t[1]))
--nil
--number

Subscript 0 is printed as a null value

2.2 Use... to concatenate strings

Unlike most languages ​​using +, Lua uses two dots to concatenate strings:

print('hello' .. ', world')

2.3 There is only a data structure of table

There is only one data structure in Lua, and that is table, which can include arrays and hash tables:

local color = {
    
    first = "red", "blue", third = "green", "yellow"}
print(color["first"])                 --> output: red
print(color[1])                         --> output: blue
print(color["third"])                --> output: green
print(color[2])                         --> output: yellow
print(color[3])                         --> output: nil

If you don't explicitly assign values ​​in _key-value pairs_, the table will use numbers as subscripts by default, starting from 1. So color[1] is blue.

In addition, it is not easy to get the correct length in the table

local t1 = {
    
     1, 2, 3 }
print("Test1 " .. table.getn(t1))

local t2 = {
    
     1, a = 2, 3 }
print("Test2 " .. table.getn(t2))

local t3 = {
    
     1, nil }
print("Test3 " .. table.getn(t3))
--Test1 3
--Test2 2
--Test3 1

To get the table length in Lua, you must note that only when the table is a'sequence' can the correct value be returned.

So what is a sequence? First, the sequence is a subset of the array, that is, the elements in the table can be accessed with a positive integer subscript, and there is no key-value pair. Corresponding to the above code, except for t2, all other tables are arrays.

Secondly, the sequence does not contain holes, that is, nil. Taking these two points together, in the table above, t1 is a sequence, and t3 is an array, but not a sequence.

2.4 The default is a global variable

When declaring a variable in Lua, you must add local before it

local s = 'hello'

This is because in Lua, variables are global by default and will be placed in a table named _G. Variables without local will be looked up in the global table, which is an expensive operation. If you add some spelling errors in the variable name, it will cause a bug that is difficult to locate.

Therefore, it is strongly recommended to always use local to declare variables, even when requiring module:

-- Recommended 
local xxx = require('xxx')
-- Avoid
require('xxx')

Guess you like

Origin blog.csdn.net/qq_33873431/article/details/112213724