Lua learning (2)

Continuing with the content of the previous article. Lua learning (1)

7. lua function

Functions are the primary way to abstract statements and expressions

optional_function_scope function function_name( argument1, argument2, argument3..., argumentn)
    function_body
    return result_params_comma_separated
end
  • optional_function_scope: This parameter is optional to specify whether the function is a global function or a local function. If this parameter is not set, it defaults to a global function. If you need to set the function to a local function, you need to use the keyword local .
  • function_name: Specify the function name.
  • argument1, argument2, argument3…, argumentn: function parameters, multiple parameters are separated by commas, and the function can also have no parameters.
  • function_body: function body, the block of code statements that need to be executed in the function.
  • result_params_comma_separated: function return value, Lua language function can return multiple values, each value is separated by commas.

8. Lua operators

8.1 Arithmetic operators

The following table lists the commonly used arithmetic operators in Lua language. Set the value of A to 10 and the value of B to 20:

Operator describe Example
+ addition A + B output result 30
- Subtraction A - B output result -10
* multiplication A * B output result 200
/ division B / A output result 2
% Take remainder B % A output result 0
^ Exponentiation A^2 outputs 100
- negative -A output result -10
// Integer division operator (>=lua5.3) 5//2 output result 2
8.2 Relational operators

The following table lists the commonly used relational operators in Lua language. Set the value of A to 10 and the value of B to 20:

Operator describe Example
== Equal, detects whether two values ​​are equal, returns true if equal, otherwise returns false (A == B) is false.
~= Not equal, detects whether two values ​​​​are equal, returns true if not equal, otherwise returns false (A ~= B) is true.
> Greater than, if the value on the left is greater than the value on the right, returns true, otherwise returns false (A > B) is false.
< Less than, if the value on the left is greater than the value on the right, return false, otherwise return true (A < B) is true.
>= Greater than or equal to, if the value on the left is greater than or equal to the value on the right, return true, otherwise return false (A >= B) returns false.
<= Less than or equal to, if the value on the left is less than or equal to the value on the right, return true, otherwise return false (A <= B) returns true.
8.3 Logical operators

The table lists the commonly used logical operators in Lua language. Set the value of A to true and the value of B to false:

Operator describe Example
and Logical AND operator. If A is false, return A, otherwise return B. (A and B) is false.
or Logical OR operator. If A is true, return A, otherwise return B. (A or B) 为 true。
not Logical NOT operator. Contrary to the result of a logical operation, if the condition is true, the logical negation is false. not(A and B) 为 true。
8.4 Other operators

The following table lists the concatenation operators and operators for calculating the length of tables or strings in the Lua language:

Operator describe Example
Concatenate two strings a...b, where a is "Hello", b is "World", and the output result is "Hello World".
# Unary operator that returns the length of a string or table. #"Hello" returns 5

9. lua string

String is a basic data type used to store text data. Strings in Lua can contain any characters, including letters, numbers, symbols, spaces, and other special characters.

--- 无论是单引号还是双引号 都是string
s = "nimaho1233"

string.len(s) --- 字符串的长度

9.1 String formatting
local sourcestr = "prefix--runoobgoogletaobao--suffix"
print("\n原始字符串", string.format("%q", sourcestr))

-- 截取部分,第4个到第15个
local first_sub = string.sub(sourcestr, 4, 15)
print("\n第一次截取", string.format("%q", first_sub))

-- 取字符串前缀,第1个到第8个
local second_sub = string.sub(sourcestr, 1, 8)
print("\n第二次截取", string.format("%q", second_sub))

-- 截取最后10个
local third_sub = string.sub(sourcestr, -10)
print("\n第三次截取", string.format("%q", third_sub))

-- 索引越界,输出原始字符串
local fourth_sub = string.sub(sourcestr, -100)
print("\n第四次截取", string.format("%q", fourth_sub))
  • %c - accepts a number and converts it to the corresponding character in the ASCII code table
  • %d, %i - accept a number and convert it to signed integer format
  • %f - takes a number and converts it to floating point format
  • %g(%G) - accepts a number and converts it to the shorter format of %e(%E, corresponding to %G) or %f
  • %q - takes a string and converts it into a format that can be safely read by the Lua compiler
  • %s - accepts a string and formats it according to the given parameters
  • %o - takes a number and converts it to octal format
  • %u - accepts a number and converts it to unsigned integer format
  • %x - takes a number and converts it to hexadecimal format, using lowercase letters
  • %X - takes a number and converts it to hexadecimal format, using uppercase letters
  • %e - takes a number and converts it to scientific notation, using lowercase e
  • %E - takes a number and converts it to scientific notation, using uppercase E
string.find (str, substr, [init, [plain]])
在一个指定的目标字符串 str 中搜索指定的内容 substr,如果找到了一个匹配的子串,就会返回这个子串的起始索引和结束索引,不存在则返回 nil

-----init 指定了搜索的起始位置,默认为 1,可以一个负数,表示从后往前数的字符个数。

-----lain 表示是否使用简单模式,默认为 false,true 只做简单的查找子串的操作,false 表示使用使用正则模式匹配。

----- 以下实例查找字符串 "Lua" 的起始索引和结束索引位置:
string.find("Hello Lua user", "Lua", 1) 

string.format(...)
返回一个类似printf的格式化字符串
> string.format("the value is:%d",4)
the value is:4
9.2 Matching patterns
  • .(dot): Pairs with any character

  • %a: matches any letter

  • %c: paired with any control character (e.g. \n)

  • %d: matches any number

  • %l: Pairs with any lowercase letter

  • %p: matches any punctuation

  • %s: paired with whitespace characters

  • %u: Pairs with any uppercase letter

  • %w: matches any letter/number

  • %x: Pairs with any hexadecimal number

  • %z: Pairs with any character representing 0

  • %x (where x is a non-alphanumeric character): paired with the character x. Mainly used to deal with the matching of functional characters (^$()%.[]*±?) in expressions, such as %% and %pair

  • [Several character classes]: Matches any character class contained in []. For example, [%w_] matches any letter/number, or underscore symbol (_)

  • A single character class matches any single character in that class;

  • A single character class followed by ' *' will match zero or more characters of that class. This entry always matches the longest possible string;

  • A single character class followed by ' +' will match one or more characters of that class. This entry always matches the longest possible string;

  • A single character class followed by ' -' will match zero or more characters of that class. Unlike ' *', this entry always matches the shortest possible string;

  • A single character class followed by ' ?' will match zero or one characters of that class. Whenever possible, it will match one;

  • %*n*, where n can range from 1 to 9; this entry matches a substring equal to capture number n (described later).

10. lua array

An array is a collection of elements of the same data type arranged in a certain order. It can be a one-dimensional array or a multi-dimensional array. In Lua, an array is not a specific data type, but a data structure used to store a set of values. In fact, there is no special array type in Lua. Instead, a data structure called a "table" is used to implement the functions of an array.

To sum up, there is no array in Lua. What is actually used here is table.

-- 创建一个数组
local myArray = {
    
    10, 20, 30, 40, 50}

-- 访问数组元素
print(myArray[1])  -- 输出 10
print(myArray[3])  -- 输出 30
function init()
    local myArray = {
    
    }
    for i = 1, 10 do
        myArray[i]=i
    end
    for i, v in ipairs(myArray) do
        print(v)
    end
end
--- 初始化

11. lua iterator

An iterator is an object that can be used to traverse some or all elements in a standard template library container. Each iterator object represents a certain address in the container.

for k, v in pairs(t) do
    print(k, v)
end
上面代码中,k, v为变量列表;pairs(t)为表达式列表。

-----------------------------------
function Iterators()
    local list = {
    
    "稳健打团","天意不可违","格局","莎莉","虞姬"}

    for key, value in pairs(list) do
        print(string.format("我是key:%02s 我是value:%s",key,value))
    end
end

Iterators()
11.1 Lua table

Table is a data structure in Lua that helps us create different data types, such as arrays, dictionaries, etc. Lua table uses associative arrays. You can use any type of value as an array index, but this value cannot be nil.

-- 初始化表
mytable = {
    
    }

-- 指定值
mytable[1]= "Lua"

-- 移除引用
mytable = nil
-- lua 垃圾回收会释放内存

When we set the elements for table a and then assign a to b, both a and b point to the same memory. If a is set to nil, b can also access the elements of the table. If there is no specified variable pointing to a, Lua's garbage collection mechanism will clean up the corresponding memory.

tables = {
    
    }
print(type(tables)) -- 查看table的类型

function TestTable(length)
    local myTable = {
    
    }
    for i = 1, length do
        myTable[i] = i*2+1;
        print(myTable[i])
    end
    myTable["tt"] = "恐龙"
    print(myTable["tt"])
end

TestTable(10)


table method

table.concat (table [, sep [, start [, end]]])
参数中指定table的数组部分从start位置到end位置的所有元素, 元素间以指定的分隔符(sep)隔开。

table.sort (table [, comp])
对给定的table进行升序排序。

table.insert (table, [pos,] value):
在table的数组部分指定位置(pos)插入值为value的一个元素. pos参数可选, 默认为数组部分末尾.

table.remove (table [, pos])
返回table数组部分位于pos位置的元素. 其后的元素会被前移. pos参数可选, 默认为table长度, 即从最后一个元素删起。	
function TestMethod()
    fruits = {
    
    "banana","orange","apple","Watermelon","persimmon"}
    list = {
    
    1,2,3,4,5,89,0}
    --print(table.concat(fruits,","))
    --print(table.concat(fruits))

    table.sort(list)
    table.insert(list,10)
    print("排序后")
    for i,v in ipairs(list) do
        print(i,v)
    end
end
TestMethod()

12. lua module

A module is similar to a package library. Starting from Lua 5.1, Lua has added a standard module management mechanism, which allows you to put some common code in a file and call it in other places in the form of an API interface, which is conducive to code reuse and reduction. Code coupling. The module is a table structure and is very simple

--- 首先声明一下一个模块并且要和lua文件名一样
model = {
    
    }

model.const ="我是常量"

--- 公共函数
function model.fun1()
    print("我是共有函数")
end

--- 私有函数
function fun2()
    print("我是私有函数")
end

function model.fun3()
    fun2()
end
--- 最后需要返回
return model
--- 使用的时候只需要 使用require函数即可

local model =require("models")
print(model.fun3())
12.1 Loading mechanism

For custom modules, the module file does not matter which file directory it is placed in. The function require has its own file path loading strategy, and it will try to load the module from a Lua file or C library. The path used by require to search for Lua files is stored in the global variable package.path. When Lua is started, this environment variable will be initialized with the value of the environment variable LUA_PATH. If the environment variable is not found, a default path defined at compile time is used for initialization.

12.2 C package

Lua and C are easily combined. Use C to write packages for Lua. Unlike packages written in Lua, C packages must first be loaded and connected before use. In most systems, the easiest way to implement this is through the dynamic link library mechanism.

local path = "/luaDownload/lua-5.4.6/lib/libluasocket.so"
local f = loadlib(path, "luaopen_socket")

The loadlib function loads the specified library and connects to Lua. However, it does not open the library (that is, it does not call the initialization function). Instead, it returns the initialization function as a function in Lua, so that we can call it directly in Lua. If an error occurs while loading a dynamic library or locating an initialization function, loadlib will return nil and an error message. We can modify the previous code so that it detects errors and then calls the initialization function:

local path = "/luaDownload/lua-5.4.6/lib/libluasocket.so"
-- 或者 path = "C:\\windows\\luasocket.dll",这是 Window 平台下
local f = assert(loadlib(path, "luaopen_socket"))
f()  -- 真正打开库

Guess you like

Origin blog.csdn.net/m0_52021450/article/details/132569356