跟着 Lua 5.1 官方参考文档学习 Lua (10)

文章目录

    • 5.2 – Coroutine Manipulation
      • `coroutine.create (f)`
      • `coroutine.resume (co [, val1, ···])`
      • `coroutine.running ()`
      • `coroutine.status (co)`
        • 例子:**协程的状态**
      • `coroutine.wrap (f)`
      • `coroutine.yield (···)`
    • 5.3 – Modules
      • `module (name [, ···])`
      • `require (modname)`
      • `package.loaded`
      • `package.loaders`
      • `package.preload`
      • `package.path`
      • `package.cpath`
      • `package.loadlib (libname, funcname)`
        • 例子:package.loadlib 的使用
      • `package.seeall (module)`
    • 5.4 – String Manipulation
      • `string.byte (s [, i [, j]])`
      • `string.char (···)`
        • 例子:string.byte 和 string.char 的使用
      • `string.format (formatstring, ···)`
        • 例子:string.format 的使用
      • `string.len (s)`
      • `string.lower (s)`
      • `string.upper (s)`
      • `string.rep (s, n)`
      • `string.reverse (s)`
      • `string.sub (s, i [, j])`
      • `string.dump (function)`

5.2 – Coroutine Manipulation

The operations related to coroutines comprise a sub-library of the basic library and come inside the table coroutine. See §2.11 for a general description of coroutines.

coroutine.create (f)

Creates a new coroutine, with body f. f must be a Lua function. Returns this new coroutine, an object with type "thread".

coroutine.resume (co [, val1, ···])

Starts or continues the execution of coroutine co. The first time you resume a coroutine, it starts running its body. The values val1, ··· are passed as the arguments to the body function. If the coroutine has yielded, resume restarts it; the values val1, ··· are passed as the results from the yield.

If the coroutine runs without any errors, resume returns true plus any values passed to yield (if the coroutine yields) or any values returned by the body function (if the coroutine terminates). If there is any error, resume returns false plus the error message.

coroutine.running ()

Returns the running coroutine, or nil when called by the main thread.

coroutine.status (co)

Returns the status of coroutine co, as a string:

"running", if the coroutine is running (that is, it called status);

"suspended", if the coroutine is suspended in a call to yield, or if it has not started running yet;

"normal" if the coroutine is active but not running (that is, it has resumed another coroutine);

and "dead" if the coroutine has finished its body function, or if it has stopped with an error.

例子:协程的状态
-- 创建一个协程
local co
co = coroutine.create(function()print("协程1开始执行")-- 检查协程状态,应该是runningprint("协程1状态: " .. coroutine.status(co)) -- "running"local co2 = coroutine.create(function()print("协程2开始执行")print("协程2里的协程1状态: " .. coroutine.status(co)) -- "normal"print("协程2执行结束")end)-- 启动协程2coroutine.resume(co2)coroutine.yield() -- 暂停协程print("协程1恢复执行")
end)-- 初始状态:协程被创建但未执行,所以状态是"suspended"
print("协程1初始状态: " .. coroutine.status(co)) -- "suspended"-- 启动协程
coroutine.resume(co)-- 在协程内部调用status,应该输出"running"
-- 输出会在协程内部看到,表明此时协程正在执行
print("协程1执行后,状态: " .. coroutine.status(co)) -- "suspended"(外部查看状态,仍然是suspended)-- 恢复协程
coroutine.resume(co)-- 最后,协程结束,状态变为"dead"
print("协程1结束后的状态: " .. coroutine.status(co)) -- "dead"

输出

协程1初始状态: suspended
协程1开始执行
协程1状态: running
协程2开始执行
协程2里的协程1状态: normal
协程2执行结束
协程1执行后,状态: suspended
协程1恢复执行
协程1结束后的状态: dead

coroutine.wrap (f)

Creates a new coroutine, with body f. f must be a Lua function. Returns a function that resumes the coroutine each time it is called. Any arguments passed to the function behave as the extra arguments to resume. Returns the same values returned by resume, except the first boolean. In case of error, propagates the error.

coroutine.yield (···)

Suspends the execution of the calling coroutine. The coroutine cannot be running a C function, a metamethod, or an iterator. Any arguments to yield are passed as extra results to resume.

协程的例子见这篇文章

5.3 – Modules

The package library provides basic facilities for loading and building modules in Lua. It exports two of its functions directly in the global environment: require and module. Everything else is exported in a table package.

module (name [, ···])

忽略,基本不使用

require (modname)

Loads the given module. The function starts by looking into the package.loaded table to determine whether modname is already loaded. If it is, then require returns the value stored at package.loaded[modname]. Otherwise, it tries to find a loader for the module.

To find a loader, require is guided by the package.loaders array. By changing this array, we can change how require looks for a module. The following explanation is based on the default configuration for package.loaders.【见package.loaders中的说明】

First require queries package.preload[modname]. If it has a value, this value (which should be a function) is the loader. Otherwise require searches for a Lua loader using the path stored in package.path. If that also fails, it searches for a C loader using the path stored in package.cpath. If that also fails, it tries an all-in-one loader (see package.loaders).

Once a loader is found, require calls the loader with a single argument, modname. If the loader returns any value, require assigns the returned value to package.loaded[modname]. If the loader returns no value and has not assigned any value to package.loaded[modname], then require assigns true to this entry. In any case, require returns the final value of package.loaded[modname].

If there is any error loading or running the module, or if it cannot find any loader for the module, then require signals an error.

package.loaded

A table used by require to control which modules are already loaded. When you require a module modname and package.loaded[modname] is not false, require simply returns the value stored there.

package.loaders

A table used by require to control how to load modules.

Each entry in this table is a searcher function. When looking for a module, require calls each of these searchers in ascending order, with the module name (the argument given to require) as its sole parameter. The function can return another function (the module loader) or a string explaining why it did not find that module (or nil if it has nothing to say). Lua initializes this table with four functions.

The first searcher simply looks for a loader in the package.preload table.

The second searcher looks for a loader as a Lua library, using the path stored at package.path. A path is a sequence of templates separated by semicolons. For each template, the searcher will change each interrogation mark in the template by filename, which is the module name with each dot replaced by a “directory separator” (such as “/” in Unix); then it will try to open the resulting file name. So, for instance, if the Lua path is the string

     "./?.lua;./?.lc;/usr/local/?/init.lua"

the search for a Lua file for module foo will try to open the files ./foo.lua, ./foo.lc, and /usr/local/foo/init.lua, in that order.

The third searcher looks for a loader as a C library, using the path given by the variable package.cpath. For instance, if the C path is the string

     "./?.so;./?.dll;/usr/local/?/init.so"

the searcher for module foo will try to open the files ./foo.so, ./foo.dll, and /usr/local/foo/init.so, in that order. Once it finds a C library, this searcher first uses a dynamic link facility to link the application with the library. Then it tries to find a C function inside the library to be used as the loader. The name of this C function is the string “luaopen_” concatenated with a copy of the module name where each dot is replaced by an underscore. Moreover, if the module name has a hyphen, its prefix up to (and including) the first hyphen is removed. For instance, if the module name is a.v1-b.c, the function name will be luaopen_b_c.

The fourth searcher tries an all-in-one loader. It searches the C path for a library for the root name of the given module. For instance, when requiring a.b.c, it will search for a C library for a. If found, it looks into it for an open function for the submodule; in our example, that would be luaopen_a_b_c. With this facility, a package can pack several C submodules into one single library, with each submodule keeping its original open function.

package.preload

A table to store loaders for specific modules (see require).

package.path

The path used by require to search for a Lua loader.

At start-up, Lua initializes this variable with the value of the environment variable LUA_PATH or with a default path defined in luaconf.h, if the environment variable is not defined. Any “;;” in the value of the environment variable is replaced by the default path

package.cpath

The path used by require to search for a C loader.

Lua initializes the C path package.cpath in the same way it initializes the Lua path package.path, using the environment variable LUA_CPATH or a default path defined in luaconf.h.

package.loadlib (libname, funcname)

Dynamically links the host program with the C library libname. Inside this library, looks for a function funcname and returns this function as a C function. (So, funcname must follow the protocol (see lua_CFunction)).

This is a low-level function. It completely bypasses the package and module system. Unlike require, it does not perform any path searching and does not automatically adds extensions. libname must be the complete file name of the C library, including if necessary a path and extension. funcname must be the exact name exported by the C library (which may depend on the C compiler and linker used).

This function is not supported by ANSI C. As such, it is only available on some platforms (Windows, Linux, Mac OS X, Solaris, BSD, plus other Unix systems that support the dlfcn standard).

例子:package.loadlib 的使用

mylib.c

#include <lua.h>
#include <lauxlib.h>
#include <lualib.h>// C 函数:加法
int add(lua_State *L) {// 从栈中获取两个参数double a = luaL_checknumber(L, 1);double b = luaL_checknumber(L, 2);// 将结果推送到 Lua 栈上lua_pushnumber(L, a + b);return 1;  // 返回一个结果
}// 导出函数
int luaopen_mylib(lua_State *L) {lua_register(L, "add", add);  // 注册 add 函数return 0;
}

编译

gcc -o mylib.so -shared mylib.c -fPIC -I/usr/local/include/luajit-2.1 -lluajit-5.1

lua代码

-- 使用 package.loadlib 加载共享库
local lib = package.loadlib("./mylib.so", "luaopen_mylib")-- 加载库后,调用返回的函数
lib()  -- 这会注册 C 库中的 "add" 函数到 Lua 环境-- 调用 "add" 函数,传递两个数字
local result = add(10, 20)
print("结果:", result)  -- 输出: 结果: 30

package.seeall (module)

忽略,基本不使用

5.4 – String Manipulation

This library provides generic functions for string manipulation, such as finding and extracting substrings, and pattern matching. When indexing a string in Lua, the first character is at position 1 (not at 0, as in C). Indices are allowed to be negative and are interpreted as indexing backwards, from the end of the string. Thus, the last character is at position -1, and so on.

The string library provides all its functions inside the table string. It also sets a metatable for strings where the __index field points to the string table. Therefore, you can use the string functions in object-oriented style. For instance, string.byte(s, i) can be written as s:byte(i).

The string library assumes one-byte character encodings.

string.byte (s [, i [, j]])

Returns the internal numerical codes of the characters s[i], s[i+1], ···, s[j]. The default value for i is 1; the default value for j is i.

Note that numerical codes are not necessarily portable across platforms.

string.char (···)

Receives zero or more integers. Returns a string with length equal to the number of arguments, in which each character has the internal numerical code equal to its corresponding argument.

Note that numerical codes are not necessarily portable across platforms.

例子:string.byte 和 string.char 的使用
local bytes = { string.byte("hello", 1, #("hello")) }
for i, b in ipairs(bytes) doprint(b)  -- 输出 'h', 'e', 'l', 'l', 'o' 的字节值 104 101 108 108 111
endprint(string.char(104, 101, 108, 108, 111)) -- 输出 hello

string.format (formatstring, ···)

Returns a formatted version of its variable number of arguments following the description given in its first argument (which must be a string). The format string follows the same rules as the printf family of standard C functions. The only differences are that the options/modifiers *, l, L, n, p, and h are not supported and that there is an extra option, q. The q option formats a string in a form suitable to be safely read back by the Lua interpreter: the string is written between double quotes, and all double quotes, newlines, embedded zeros, and backslashes in the string are correctly escaped when written. For instance, the call

     string.format('%q', 'a string with "quotes" and \n new line')

will produce the string:

     "a string with \"quotes\" and \new line"

The options c, d, E, e, f, g, G, i, o, u, X, and x all expect a number as argument, whereas q and s expect a string.

This function does not accept string values containing embedded zeros, except as arguments to the q option.

%c - 接受一个数字,并将其转化为ASCII码表中对应的字符

%d, %i - 接受一个数字并将其转化为有符号的整数格式

%o - 接受一个数字并将其转化为八进制数格式

%u - 接受一个数字并将其转化为无符号整数格式

%x - 接受一个数字并将其转化为十六进制数格式,使用小写字母

%X - 接受一个数字并将其转化为十六进制数格式,使用大写字母

%e - 接受一个数字并将其转化为科学记数法格式,使用小写字母e

%E - 接受一个数字并将其转化为科学记数法格式,使用大写字母E

%f - 接受一个数字并将其转化为浮点数格式

%g(%G) - 接受一个数字并将其转化为%e(%E,对应%G)及%f中较短的一种格式

%q - 接受一个字符串并将其转化为可安全被Lua编译器读入的格式

%s - 接受一个字符串并按照给定的参数格式化该字符串

为进一步细化格式, 可以在%号后添加参数.参数将以如下的顺序读入:

(1) 符号:一个+号表示其后的数字转义符将让正数显示正号.默认情况下只有负数显示符号.

(2) 占位符: 一个0,在后面指定了字串宽度时占位用.不填时的默认占位符是空格.

(3) 对齐标识: 在指定了字串宽度时,默认为右对齐,增加-号可以改为左对齐.

(4) 宽度数值
(5) 小数位数/字串裁切:在宽度数值后增加的小数部分n,若后接f(浮点数转义符,如%6.3f)则设定该浮点数的小数只保留n位,若后接s(字符串转义符,如%5.3s)则设定该字符串只显示前n位.

在这些参数的后面则是上述所列的转义码类型(c, d, i, f, …).

例子:string.format 的使用
print(string.format("%%c: %c", 83))            -- %c: S
print(string.format("%+d", 17.0))              -- +17
print(string.format("%05d", 17))               -- 00017
print(string.format("%o", 17))                 -- 21
print(string.format("%u", 3.14))               -- 3
print(string.format("%x", 13))                 -- d
print(string.format("%X", 13))                 -- D
print(string.format("%e", 1000))               -- 1.000000e+03
print(string.format("%E", 1000))               -- 1.000000E+03
print(string.format("%6.3f", 13))              -- 13.000
print(string.format("%s", "monkey"))           -- monkey
print(string.format("%10s", "monkey"))         --     monkey
print(string.format("%5.3s", "monkey"))        --   mon

string.len (s)

Receives a string and returns its length. The empty string "" has length 0. Embedded zeros are counted, so "a\000bc\000" has length 5.

string.lower (s)

Receives a string and returns a copy of this string with all uppercase letters changed to lowercase. All other characters are left unchanged. The definition of what an uppercase letter is depends on the current locale.

string.upper (s)

Receives a string and returns a copy of this string with all lowercase letters changed to uppercase. All other characters are left unchanged. The definition of what a lowercase letter is depends on the current locale.

string.rep (s, n)

Returns a string that is the concatenation of n copies of the string s.

string.reverse (s)

Returns a string that is the string s reversed.

string.sub (s, i [, j])

Returns the substring of s that starts at i and continues until j; i and j can be negative. If j is absent, then it is assumed to be equal to -1 (which is the same as the string length). In particular, the call string.sub(s,1,j) returns a prefix of s with length j, and string.sub(s, -i) returns a suffix of s with length i.

string.dump (function)

Returns a string containing a binary representation of the given function, so that a later loadstring on this string returns a copy of the function. function must be a Lua function without upvalues.

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.rhkb.cn/news/29931.html

如若内容造成侵权/违法违规/事实不符,请联系长河编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

【FSM-3: 串行序列】

FSM-3&#xff1a;串行序列 1 Serial receiver FSM使用总结&#xff1a; 所有涉及输出的driver原则上用cur_sta&#xff1b;若是使用nxt_sta的相当于是提前一拍知道结果&#xff0c;所以对于输出必须要使用clocked reg&#xff0c;这样才能和cur_sta对应起来&#xff1b;描述声…

蓝桥杯 之 前缀和与查分

文章目录 题目求和棋盘挖矿 前缀和有利于快速求解 区间的和、异或值 、乘积等情况差分是前缀和的反操作 前缀和 一维前缀和&#xff1a; # 原始的数组num,下标从1到n n len(num) pre [0]*(n1) for i in range(n):pre[i1] pre[i] num[i] # 如果需要求解num[l] 到num[r] 的区…

国产化板卡设计原理图:2330-基于FMC接口的JFM7K325T PCIeX4 3U PXIe接口卡

基于FMC接口的JFM7K325T PCIeX4 3U PXIe接口卡 一、板卡概述 本板卡基于 FPGAJFM7K325T 芯片&#xff0c;pin_to_pin兼容FPGAXC7K410T-2FFG900 &#xff0c;支持PCIeX8、64bit DDR3容量2GByte&#xff0c;HPC的FMC连接器&#xff0c;板卡支持PXIE标准协议&#xff0c;其中XJ3…

计算机视觉之dlib人脸关键点绘制及微笑测试

dlib人脸关键点绘制及微笑测试 目录 dlib人脸关键点绘制及微笑测试1 dlib人脸关键点1.1 dlib1.2 人脸关键点检测1.3 检测模型1.4 凸包1.5 笑容检测1.6 函数 2 人脸检测代码2.1 关键点绘制2.2 关键点连线2.3 微笑检测 1 dlib人脸关键点 1.1 dlib dlib 是一个强大的机器学习库&a…

一周学会Flask3 Python Web开发-SQLAlchemy连接Mysql数据库

锋哥原创的Flask3 Python Web开发 Flask3视频教程&#xff1a; 2025版 Flask3 Python web开发 视频教程(无废话版) 玩命更新中~_哔哩哔哩_bilibili app.py下&#xff0c;我们先配置数据库连接&#xff0c;然后写一个简单sql测试。 连接配置&#xff0c;包括用户名&#xff…

blender看不到导入的模型

参考&#xff1a;blender 快捷键 常见问题_blender材质预览快捷键-CSDN博客 方法一&#xff1a;视图-裁剪起点&#xff0c;设置一个很大的值 方法二&#xff1a;选中所有对象&#xff0c;对齐视图-视图对齐活动项-选择一个视图

CES Asia 2025增设未来办公教育板块,科技变革再掀高潮

作为亚洲消费电子领域一年一度的行业盛会&#xff0c;CES Asia 2025&#xff08;第七届亚洲消费电子技术贸易展&#xff09;即将盛大启幕。今年展会规模再度升级&#xff0c;预计将吸引超过500家全球展商参展&#xff0c;专业观众人数有望突破10万。除了聚焦人工智能、物联网、…

【目标检测】【NeuralPS 2023】Gold-YOLO:通过收集与分发机制实现的高效目标检测器

Gold-YOLO&#xff1a; Efficient Object Detector via Gather-and-Distribute Mechanism Gold-YOLO&#xff1a;通过收集与分发机制实现的高效目标检测器 0.论文摘要 在过去的几年中&#xff0c;YOLO系列模型已成为实时目标检测领域的领先方法。许多研究通过修改架构、增强数…

利用python实现对Excel文件中数据元组的自定义排序

问题引入&#xff1a; 假设你是一个浙江省水果超市的老板&#xff0c;统筹11个下辖地市的水果产量。假设11个地市生产的水果包括&#xff1a;苹果、香蕉和西瓜。你如何快速得到某种水果产量突出&#xff08;排名前几&#xff09;的地市&#xff1f;产量落后&#xff08;排名后…

数学建模笔记——层次分析法(AHP)

本文借鉴了数学建模清风老师的视频和课件,如有错误欢迎大家批评指正。原视频地址:清风数学建模:https://www.bilibili.com/video/BV1DW411s7wihttps://www.bilibili.com/video/BV1DW411s7wi 1.预备知识 层次分析法: 层次分析法(The Analytic Hierarchy Process,AHP)是一…

koa-session设置Cookie后获取不到

在谷歌浏览器中请求获取不到cookie问题之一&#xff08;谷歌安全策略&#xff09; 场景 前端使用 axios 请求&#xff0c;项目地址&#xff1a;http://192.168.8.1:5173 import axios from axiosconst request axios.create({baseURL: http://127.0.0.1:3001/,timeout: 60000,…

Greenplum6.19集群搭建

一&#xff0c;安装说明 1.1环境说明 1、首先确定部署的环境&#xff0c;确定下服务器的端口&#xff0c;一般默认是22的端口&#xff1b; 2、当前这份文档是服务器处于10022端口下部署的&#xff08;现场生产环境要求&#xff0c;22端口在生产环境存在安全隐患&#xff09;&…

SAP DOI EXCEL宏的使用

OAOR里上传EXCEL模版 屏幕初始化PBO创建DOI EXCEL对象&#xff0c;并填充EXCEL内容 *&---------------------------------------------------------------------* *& Module INIT_DOI_DISPLAY_9100 OUTPUT *&--------------------------------------------…

排序算法漫游:从冒泡到堆排的底层逻辑与性能厮杀

各位看官早安午安晚安呀 如果您觉得这篇文章对您有帮助的话 欢迎您一键三连&#xff0c;小编尽全力做到更好 欢迎您分享给更多人哦 今天我们来学习七大排序算法 一&#xff1a;直接插入排序 直接插入排序是一种简单的插入排序法&#xff0c;其基本思想是&#xff1a; 把待排序…

【VBA】WPS/PPT设置标题字体

通过VBA&#xff0c;配合左上角的快速访问工具栏&#xff0c;实现自动化调整 选中文本框的 字体位置、大小、颜色。 配合quicker更加便捷 Sub DisableAutoWrapAndFormat()Dim shp As Shape 检查是否选中了一个形状&#xff08;文本框&#xff09;If ActiveWindow.Selection.Typ…

大语言模型从理论到实践(第二版)-学习笔记(绪论)

大语言模型的基本概念 1.理解语言是人工智能算法获取知识的前提 2.语言模型的目标就是对自然语言的概率分布建模 3.词汇表 V 上的语言模型&#xff0c;由函数 P(w1w2 wm) 表示&#xff0c;可以形式化地构建为词序列 w1w2 wm 的概率分布&#xff0c;表示词序列 w1w2 wm…

Qt常用控件之 纵向列表QListWidget

纵向列表QListWidget QListWidget 是一个纵向列表控件。 QListWidget属性 属性说明currentRow当前被选中的是第几行。count一共有多少行。sortingEnabled是否允许排序。isWrapping是否允许换行。itemAlignment元素的对齐方式。selectRectVisible被选中的元素矩形是否可见。s…

使用 Apache POI 实现 Excel 单元格合并

在日常工作中&#xff0c;Excel 是一个不可或缺的工具&#xff0c;尤其是在处理大量数据时。为了提升数据的可读性和美观性&#xff0c;我们经常需要对 Excel 中的单元格进行合并操作。本文将介绍如何使用 Apache POI 库在 Java 中实现 Excel 单元格的合并&#xff0c;并提供一…

leetcode日记(84)交错字符串

很明显的动态规划&#xff0c;就是怎么用想了一段时间。&#xff08;开始还怀疑过是不是双指针&#xff0c;发现不行&#xff0c;因为会出现s3的下一个字符同时能够匹配到两个字符串字符的情况&#xff09; 然后就是构建数组dp[101][101]&#xff0c;数组代表前x个s1字符和前y…

【Linux———信号精讲】

你是怎么做到的&#xff0c;给了她想要的爱............................................................................................ 文章目录 前言 一、【信号入门】 1.1、【生活角度的信号】 1.2、【ctrl c与z】 1.3、【信号的发送与记录】 1.4、【信号处理常见方式…