6 – 标准库

原文:https://www.lua.org/manual/5.4/manual.html

6 – The Standard Libraries – 标准库

The standard Lua libraries provide useful functions that are implemented in C through the C API. Some of these functions provide essential services to the language (e.g., type and getmetatable); others provide access to outside services (e.g., I/O); and others could be implemented in Lua itself, but that for different reasons deserve an implementation in C (e.g., table.sort).

​ Lua 标准库提供了通过 C API 在 C 中实现的有用函数。其中一些函数为该语言提供基本服务(例如, typegetmetatable );其他函数提供对外部服务的访问(例如,I/O);而其他函数可以在 Lua 本身中实现,但出于不同的原因值得在 C 中实现(例如, table.sort )。

All libraries are implemented through the official C API and are provided as separate C modules. Unless otherwise noted, these library functions do not adjust its number of arguments to its expected parameters. For instance, a function documented as foo(arg) should not be called without an argument.

​ 所有库都是通过官方 C API 实现的,并作为单独的 C 模块提供。除非另有说明,否则这些库函数不会调整其参数的预期参数数量。例如,记录为 foo(arg) 的函数不应在没有参数的情况下调用。

The notation fail means a false value representing some kind of failure. (Currently, fail is equal to nil, but that may change in future versions. The recommendation is to always test the success of these functions with (not status), instead of (status == nil).)

​ fail 表示某种失败的错误值。(目前,fail 等于 nil,但可能在未来版本中发生改变。建议始终使用 (not status) 来测试这些函数的成功,而不是 (status == nil) 。)

Currently, Lua has the following standard libraries:

​ 目前,Lua 具有以下标准库:

  • basic library (§6.1); 基本库(§6.1);
  • coroutine library (§6.2); 协程库(§6.2);
  • package library (§6.3); 包库(§6.3);
  • string manipulation (§6.4); 字符串操作(§6.4);
  • basic UTF-8 support (§6.5); 基本 UTF-8 支持(§6.5);
  • table manipulation (§6.6); 表操作(§6.6);
  • mathematical functions (§6.7) (sin, log, etc.); 数学函数(§6.7)(sin、log 等);
  • input and output (§6.8); 输入和输出(§6.8);
  • operating system facilities (§6.9); 操作系统设施(§6.9);
  • debug facilities (§6.10). 调试设施(§6.10)。

Except for the basic and the package libraries, each library provides all its functions as fields of a global table or as methods of its objects.

​ 除了基本库和包库外,每个库都以全局表字段或其对象的方法的形式提供所有函数。

To have access to these libraries, the C host program should call the luaL_openlibs function, which opens all standard libraries. Alternatively, the host program can open them individually by using luaL_requiref to call luaopen_base (for the basic library), luaopen_package (for the package library), luaopen_coroutine (for the coroutine library), luaopen_string (for the string library), luaopen_utf8 (for the UTF-8 library), luaopen_table (for the table library), luaopen_math (for the mathematical library), luaopen_io (for the I/O library), luaopen_os (for the operating system library), and luaopen_debug (for the debug library). These functions are declared in lualib.h.

​ 要访问这些库,C 宿主程序应调用 luaL_openlibs 函数,该函数打开所有标准库。或者,宿主程序可以使用 luaL_requiref 调用 luaopen_base (对于基本库)、 luaopen_package (对于包库)、 luaopen_coroutine (对于协程库)、 luaopen_string (对于字符串库)、 luaopen_utf8 (对于 UTF-8 库)、 luaopen_table (对于表库)、 luaopen_math (对于数学库)、 luaopen_io (对于 I/O 库)、 luaopen_os (对于操作系统库)和 luaopen_debug (对于调试库)来单独打开它们。这些函数在 lualib.h 中声明。

6.1 – Basic Functions 基本函数

The basic library provides core functions to Lua. If you do not include this library in your application, you should check carefully whether you need to provide implementations for some of its facilities.

​ 基本库为 Lua 提供核心函数。如果您在应用程序中不包含此库,则应仔细检查是否需要为其某些设施提供实现。

assert (v [, message])

Raises an error if the value of its argument v is false (i.e., nil or false); otherwise, returns all its arguments. In case of error, message is the error object; when absent, it defaults to “assertion failed!

​ 如果其参数 v 的值为假(即 nil 或 false),则引发错误;否则,返回其所有参数。如果发生错误, message 是错误对象;如果不存在,则默认为“ assertion failed!

collectgarbage ([opt [, arg]])

This function is a generic interface to the garbage collector. It performs different functions according to its first argument, opt:

​ 此函数是垃圾回收器的通用接口。它根据其第一个参数 opt 执行不同的函数:

  • "collect": Performs a full garbage-collection cycle. This is the default option. “ collect ”:执行完整的垃圾回收周期。这是默认选项。
  • "stop": Stops automatic execution of the garbage collector. The collector will run only when explicitly invoked, until a call to restart it. “ stop ”:停止垃圾回收器的自动执行。回收器仅在显式调用时运行,直到调用重新启动它。
  • "restart": Restarts automatic execution of the garbage collector. “ restart ”:重新启动垃圾回收器的自动执行。
  • "count": Returns the total memory in use by Lua in Kbytes. The value has a fractional part, so that it multiplied by 1024 gives the exact number of bytes in use by Lua. “ count ”:以 KB 为单位返回 Lua 使用的总内存。该值具有小数部分,因此乘以 1024 可得出 Lua 使用的准确字节数。
  • "step": Performs a garbage-collection step. The step “size” is controlled by arg. With a zero value, the collector will perform one basic (indivisible) step. For non-zero values, the collector will perform as if that amount of memory (in Kbytes) had been allocated by Lua. Returns true if the step finished a collection cycle. “ step ”:执行垃圾回收步骤。步骤“大小”由 arg 控制。值为零时,回收器将执行一个基本(不可分割)步骤。对于非零值,回收器将执行相当于 Lua 已分配该内存量(以 KB 为单位)的操作。如果该步骤完成了一个收集周期,则返回 true。
  • "isrunning": Returns a boolean that tells whether the collector is running (i.e., not stopped). " isrunning “: 返回一个布尔值,指示收集器是否正在运行(即未停止)。
  • "incremental”: Change the collector mode to incremental. This option can be followed by three numbers: the garbage-collector pause, the step multiplier, and the step size (see §2.5.1). A zero means to not change that value. " incremental “: 将收集器模式更改为增量。此选项后面可以跟三个数字:垃圾收集器暂停、步长乘数和步长(请参阅 §2.5.1)。零表示不更改该值。
  • "generational”: Change the collector mode to generational. This option can be followed by two numbers: the garbage-collector minor multiplier and the major multiplier (see §2.5.2). A zero means to not change that value. " generational “: 将收集器模式更改为代际。此选项后面可以跟两个数字:垃圾收集器次要乘数和主要乘数(请参阅 §2.5.2)。零表示不更改该值。

See §2.5 for more details about garbage collection and some of these options.

​ 有关垃圾回收和其中一些选项的更多详细信息,请参阅 §2.5。

This function should not be called by a finalizer.

​ 最终确定程序不应调用此函数。

dofile ([filename])

Opens the named file and executes its content as a Lua chunk. When called without arguments, dofile executes the content of the standard input (stdin). Returns all values returned by the chunk. In case of errors, dofile propagates the error to its caller. (That is, dofile does not run in protected mode.) 打开指定的文件并将其内容作为 Lua 块执行。当不带参数调用时, dofile 执行标准输入的内容( stdin )。返回块返回的所有值。如果发生错误, dofile 将错误传播给其调用者。(即, dofile 不在受保护模式下运行。)

error (message [, level])

Raises an error (see §2.3) with message as the error object. This function never returns. 引发错误(请参阅 §2.3),其中 message 为错误对象。此函数从不返回。

Usually, error adds some information about the error position at the beginning of the message, if the message is a string. The level argument specifies how to get the error position. With level 1 (the default), the error position is where the error function was called. Level 2 points the error to where the function that called error was called; and so on. Passing a level 0 avoids the addition of error position information to the message.

​ 通常,如果消息是一个字符串, error 会在消息的开头添加一些关于错误位置的信息。 level 参数指定如何获取错误位置。在级别 1(默认)下,错误位置是调用 error 函数的位置。级别 2 将错误指向调用 error 的函数的位置;依此类推。传递级别 0 可避免向消息添加错误位置信息。

_G

A global variable (not a function) that holds the global environment (see §2.2). Lua itself does not use this variable; changing its value does not affect any environment, nor vice versa. 一个保存全局环境的全局变量(不是函数)(请参阅 §2.2)。Lua 本身不使用此变量;更改其值不会影响任何环境,反之亦然。

getmetatable (object)

If object does not have a metatable, returns nil. Otherwise, if the object’s metatable has a __metatable field, returns the associated value. Otherwise, returns the metatable of the given object.

​ 如果 object 没有元表,则返回 nil。否则,如果对象的元表具有 __metatable 字段,则返回关联的值。否则,返回给定对象的元表。

ipairs (t)

Returns three values (an iterator function, the table t, and 0) so that the construction

​ 返回三个值(一个迭代器函数、表 t 和 0),以便构造

     for i,v in ipairs(t) do body end

will iterate over the key–value pairs (1,t[1]), (2,t[2]), …, up to the first absent index.

​ 将迭代键值对( 1,t[1] )、( 2,t[2] )…,直到第一个缺失的索引。

load (chunk [, chunkname [, mode [, env]]])

Loads a chunk.

​ 加载一个块。

If chunk is a string, the chunk is this string. If chunk is a function, load calls it repeatedly to get the chunk pieces. Each call to chunk must return a string that concatenates with previous results. A return of an empty string, nil, or no value signals the end of the chunk.

​ 如果 chunk 是字符串,则块是此字符串。如果 chunk 是函数,则 load 重复调用它以获取块片段。每次调用 chunk 都必须返回一个与先前结果连接的字符串。返回空字符串、nil 或无值表示块的结束。

If there are no syntactic errors, load returns the compiled chunk as a function; otherwise, it returns fail plus the error message.

​ 如果没有语法错误,则 load 将编译的块作为函数返回;否则,它将返回失败以及错误消息。

When you load a main chunk, the resulting function will always have exactly one upvalue, the _ENV variable (see §2.2). However, when you load a binary chunk created from a function (see string.dump), the resulting function can have an arbitrary number of upvalues, and there is no guarantee that its first upvalue will be the _ENV variable. (A non-main function may not even have an _ENV upvalue.)

​ 当您加载主块时,结果函数将始终只有一个上值,即 _ENV 变量(请参阅 §2.2)。但是,当您加载从函数创建的二进制块(请参阅 string.dump )时,结果函数可以具有任意数量的上值,并且无法保证其第一个上值是 _ENV 变量。(非主函数甚至可能没有 _ENV 上值。)

Regardless, if the resulting function has any upvalues, its first upvalue is set to the value of env, if that parameter is given, or to the value of the global environment. Other upvalues are initialized with nil. All upvalues are fresh, that is, they are not shared with any other function.

​ 无论如何,如果结果函数有任何上值,则其第一个上值将设置为 env 的值(如果给定了该参数)或全局环境的值。其他上值将初始化为 nil。所有上值都是新的,即它们不会与任何其他函数共享。

chunkname is used as the name of the chunk for error messages and debug information (see §4.7). When absent, it defaults to chunk, if chunk is a string, or to “=(load)” otherwise.

chunkname 用作错误消息和调试信息的块的名称(参见 §4.7)。如果不存在,则默认为 chunk ,如果 chunk 是字符串,则默认为 " =(load) “。

The string mode controls whether the chunk can be text or binary (that is, a precompiled chunk). It may be the string “b” (only binary chunks), “t” (only text chunks), or “bt” (both binary and text). The default is “bt”.

​ 字符串 mode 控制块是文本还是二进制(即预编译块)。它可以是字符串 " b “(仅二进制块)、” t “(仅文本块)或 " bt “(二进制和文本)。默认值为 " bt “。

It is safe to load malformed binary chunks; load signals an appropriate error. However, Lua does not check the consistency of the code inside binary chunks; running maliciously crafted bytecode can crash the interpreter.

​ 加载格式错误的二进制块是安全的; load 发出适当的错误信号。但是,Lua 不会检查二进制块中代码的一致性;运行恶意编写的字节码可能会导致解释器崩溃。

loadfile ([filename [, mode [, env]]])

Similar to load, but gets the chunk from file filename or from the standard input, if no file name is given.

​ 类似于 load ,但从文件 filename 或标准输入获取块,如果没有给出文件名。

next (table [, index])

Allows a program to traverse all fields of a table. Its first argument is a table and its second argument is an index in this table. A call to next returns the next index of the table and its associated value. When called with nil as its second argument, next returns an initial index and its associated value. When called with the last index, or with nil in an empty table, next returns nil. If the second argument is absent, then it is interpreted as nil. In particular, you can use next(t) to check whether a table is empty.

​ 允许程序遍历表的所有字段。它的第一个参数是一个表,第二个参数是该表中的一个索引。对 next 的调用返回表的下一个索引及其关联的值。当使用 nil 作为第二个参数调用时, next 返回一个初始索引及其关联的值。当使用最后一个索引或在空表中使用 nil 调用时, next 返回 nil。如果缺少第二个参数,则将其解释为 nil。特别是,您可以使用 next(t) 来检查表是否为空。

The order in which the indices are enumerated is not specified, even for numeric indices. (To traverse a table in numerical order, use a numerical for.)

​ 即使对于数字索引,枚举索引的顺序也不指定。(要按数字顺序遍历表,请使用数字 for。)

You should not assign any value to a non-existent field in a table during its traversal. You may however modify existing fields. In particular, you may set existing fields to nil.

​ 在遍历表期间,您不应为表中不存在的字段分配任何值。但是,您可以修改现有字段。特别是,您可以将现有字段设置为 nil。

pairs (t)

If t has a metamethod __pairs, calls it with t as argument and returns the first three results from the call.

​ 如果 t 有元方法 __pairs ,则使用 t 作为参数调用它,并返回调用中的前三个结果。

Otherwise, returns three values: the next function, the table t, and nil, so that the construction

​ 否则,返回三个值: next 函数、表 t 和 nil,以便构造

     for k,v in pairs(t) do body end

will iterate over all key–value pairs of table t.

​ 将迭代表 t 的所有键值对。

See function next for the caveats of modifying the table during its traversal.

​ 有关在遍历期间修改表的注意事项,请参阅函数 next

pcall (f [, arg1, ···])

Calls the function f with the given arguments in protected mode. This means that any error inside f is not propagated; instead, pcall catches the error and returns a status code. Its first result is the status code (a boolean), which is true if the call succeeds without errors. In such case, pcall also returns all results from the call, after this first result. In case of any error, pcall returns false plus the error object. Note that errors caught by pcall do not call a message handler.

​ 以受保护模式使用给定参数调用函数 f 。这意味着 f 中的任何错误都不会传播;相反, pcall 会捕获错误并返回状态代码。其第一个结果是状态代码(布尔值),如果调用成功且没有错误,则为 true。在这种情况下, pcall 还会在第一个结果之后返回调用中的所有结果。如果发生任何错误, pcall 会返回 false 和错误对象。请注意, pcall 捕获的错误不会调用消息处理程序。

Receives any number of arguments and prints their values to stdout, converting each argument to a string following the same rules of tostring. 接收任意数量的参数,并将它们的值转换为字符串(遵循 tostring 的相同规则)后打印到 stdout

The function print is not intended for formatted output, but only as a quick way to show a value, for instance for debugging. For complete control over the output, use string.format and io.write.

​ 函数 print 不适用于格式化输出,而只是一种快速显示值的方式,例如用于调试。要完全控制输出,请使用 string.formatio.write

rawequal (v1, v2)

Checks whether v1 is equal to v2, without invoking the __eq metamethod. Returns a boolean. 检查 v1 是否等于 v2 ,而不调用 __eq 元方法。返回布尔值。

rawget (table, index)

Gets the real value of table[index], without using the __index metavalue. table must be a table; index may be any value. 获取 table[index] 的真实值,而不使用 __index 元值。 table 必须是表; index 可以是任何值。

rawlen (v)

Returns the length of the object v, which must be a table or a string, without invoking the __len metamethod. Returns an integer. 返回对象 v 的长度,该对象必须是表或字符串,而不调用 __len 元方法。返回一个整数。

rawset (table, index, value)

Sets the real value of table[index] to value, without using the __newindex metavalue. table must be a table, index any value different from nil and NaN, and value any Lua value. 将 table[index] 的真实值设置为 value ,而不使用 __newindex 元值。 table 必须是表, index 必须是除 nil 和 NaN 之外的任何值, value 必须是任何 Lua 值。

This function returns table.

​ 此函数返回 table

select (index, ···)

If index is a number, returns all arguments after argument number index; a negative number indexes from the end (-1 is the last argument). Otherwise, index must be the string "#", and select returns the total number of extra arguments it received.

​ 如果 index 是数字,则返回参数编号 index 之后的所有参数;负数从末尾开始索引(-1 是最后一个参数)。否则, index 必须是字符串 "#"select 返回它收到的额外参数的总数。

setmetatable (table, metatable)

Sets the metatable for the given table. If metatable is nil, removes the metatable of the given table. If the original metatable has a __metatable field, raises an error.

​ 为给定表设置元表。如果 metatable 为 nil,则删除给定表的元表。如果原始元表具有 __metatable 字段,则引发错误。

This function returns table.

​ 此函数返回 table

To change the metatable of other types from Lua code, you must use the debug library (§6.10).

​ 要从 Lua 代码更改其他类型的元表,您必须使用 debug 库(§6.10)。

tonumber (e [, base])

When called with no base, tonumber tries to convert its argument to a number. If the argument is already a number or a string convertible to a number, then tonumber returns this number; otherwise, it returns fail.

​ 当不带 base 调用时, tonumber 尝试将其参数转换为数字。如果参数已经是数字或可转换为数字的字符串,则 tonumber 返回此数字;否则,它返回失败。

The conversion of strings can result in integers or floats, according to the lexical conventions of Lua (see §3.1). The string may have leading and trailing spaces and a sign.

​ 根据 Lua 的词法惯例(参见 §3.1),字符串的转换可以产生整数或浮点数。字符串可能具有前导和尾随空格以及符号。

When called with base, then e must be a string to be interpreted as an integer numeral in that base. The base may be any integer between 2 and 36, inclusive. In bases above 10, the letter ‘A’ (in either upper or lower case) represents 10, ‘B’ represents 11, and so forth, with ‘Z’ representing 35. If the string e is not a valid numeral in the given base, the function returns fail.

​ 当带 base 调用时,则 e 必须是一个字符串,以便在该进制中解释为整数数字。进制可以是 2 到 36(包括 2 和 36)之间的任何整数。在 10 进制以上,字母“ A ”(大写或小写)表示 10,“ B ”表示 11,依此类推,“ Z ”表示 35。如果字符串 e 不是给定进制中的有效数字,则该函数返回失败。

tostring (v)

Receives a value of any type and converts it to a string in a human-readable format.

​ 接收任何类型的数值并将其转换为人类可读格式的字符串。

If the metatable of v has a __tostring field, then tostring calls the corresponding value with v as argument, and uses the result of the call as its result. Otherwise, if the metatable of v has a __name field with a string value, tostring may use that string in its final result.

​ 如果 v 的元表有一个 __tostring 字段,那么 tostring 会将相应的值作为参数调用,并将调用的结果用作其结果。否则,如果 v 的元表有一个字符串值 __name 字段, tostring 可能会在其最终结果中使用该字符串。

For complete control of how numbers are converted, use string.format.

​ 要完全控制数字的转换方式,请使用 string.format

type (v)

Returns the type of its only argument, coded as a string. The possible results of this function are “nil” (a string, not the value nil), “number”, “string”, “boolean”, “table”, “function”, “thread”, and “userdata”.

​ 返回其唯一参数的类型,编码为字符串。此函数的可能结果为“ nil ”(字符串,而不是值 nil)、“ number ”、“ string ”、“ boolean ”、“ table ”、“ function ”、“ thread ”和“ userdata ”。

_VERSION

A global variable (not a function) that holds a string containing the running Lua version. The current value of this variable is “Lua 5.4”.

​ 一个全局变量(不是函数),它保存一个包含正在运行的 Lua 版本的字符串。此变量的当前值为“ Lua 5.4 ”。

warn (msg1, ···)

Emits a warning with a message composed by the concatenation of all its arguments (which should be strings).

​ 发出警告,其消息由所有参数(应为字符串)的连接组成。

By convention, a one-piece message starting with ‘@’ is intended to be a control message, which is a message to the warning system itself. In particular, the standard warning function in Lua recognizes the control messages “@off”, to stop the emission of warnings, and “@on”, to (re)start the emission; it ignores unknown control messages.

​ 按照惯例,以“ @ ”开头的单片消息旨在成为控制消息,即发送给警告系统本身的消息。特别是,Lua 中的标准警告功能识别控制消息“ @off ”,以停止发出警告,以及“ @on ”,以(重新)开始发出警告;它忽略未知的控制消息。

xpcall (f, msgh [, arg1, ···])

This function is similar to pcall, except that it sets a new message handler msgh.

​ 此函数类似于 pcall ,不同之处在于它设置了一个新的消息处理程序 msgh

6.2 – Coroutine Manipulation 协程操作

This library comprises the operations to manipulate coroutines, which come inside the table coroutine. See §2.6 for a general description of coroutines.

​ 此库包含用于操作协程的操作,这些操作位于表 coroutine 中。有关协程的常规说明,请参阅 §2.6。

coroutine.close (co)

Closes coroutine co, that is, closes all its pending to-be-closed variables and puts the coroutine in a dead state. The given coroutine must be dead or suspended. In case of error (either the original error that stopped the coroutine or errors in closing methods), returns false plus the error object; otherwise returns true.

​ 关闭协程 co ,即关闭其所有待关闭的变量,并将协程置于死状态。给定的协程必须已死或已暂停。如果发生错误(停止协程的原始错误或关闭方法中的错误),则返回 false 加上错误对象;否则返回 true。

coroutine.create (f)

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

​ 创建一个新的协程,主体为 ff 必须是一个函数。返回此新协程,一个类型为 "thread" 的对象。

coroutine.isyieldable ([co])

Returns true when the coroutine co can yield. The default for co is the running coroutine.

​ 当协程 co 可以生成时返回 true。 co 的默认值是正在运行的协程。

A coroutine is yieldable if it is not the main thread and it is not inside a non-yieldable C function.

​ 如果协程不是主线程并且不在不可生成 C 函数内,则该协程可生成。

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.

​ 启动或继续执行协程 co 。第一次恢复协程时,它开始运行其主体。值 val1 , … 作为参数传递给主体函数。如果协程已生成,则 resume 重新启动它;值 val1 , … 作为生成的结果传递。

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

​ 如果协程在没有任何错误的情况下运行,则 resume 返回 true 加上传递给 yield 的任何值(当协程生成时)或主体函数返回的任何值(当协程终止时)。如果出现任何错误,则 resume 返回 false 加上错误消息。

coroutine.running ()

Returns the running coroutine plus a boolean, true when the running coroutine is the main one.

​ 返回正在运行的协程加上一个布尔值,当正在运行的协程为主协程时为 true。

coroutine.status (co)

Returns the status of the coroutine co, as a string: "running", if the coroutine is running (that is, it is the one that 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.

​ 返回协程 co 的状态,作为字符串: "running" ,如果协程正在运行(即,它调用了 status ); "suspended" ,如果协程在调用 yield 时挂起,或者它尚未开始运行; "normal" 如果协程处于活动状态但未运行(即,它已恢复另一个协程); "dead" 如果协程已完成其主体函数,或者它已因错误而停止。

coroutine.wrap (f)

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

​ 创建一个新的协程,主体为 ff 必须是一个函数。返回一个函数,该函数每次被调用时都会恢复协程。传递给此函数的任何参数都作为 resume 的额外参数。该函数返回 resume 返回的相同值,除了第一个布尔值。如果发生错误,该函数将关闭协程并传播错误。

coroutine.yield (···)

Suspends the execution of the calling coroutine. Any arguments to yield are passed as extra results to resume.

​ 挂起调用协程的执行。传递给 yield 的任何参数都作为额外结果传递给 resume

6.3 – Modules 模块

The package library provides basic facilities for loading modules in Lua. It exports one function directly in the global environment: require. Everything else is exported in the table package.

​ package 库为在 Lua 中加载模块提供了基本工具。它直接在全局环境中导出一个函数: require 。其他所有内容都导出到表 package 中。

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]. (The absence of a second result in this case signals that this call did not have to load the module.) Otherwise, it tries to find a loader for the module.

​ 加载给定的模块。该函数首先查看 package.loaded 表,以确定 modname 是否已加载。如果是,则 require 返回存储在 package.loaded[modname] 的值。(在这种情况下,没有第二个结果表示此调用不必加载模块。)否则,它将尝试查找模块的加载器。

To find a loader, require is guided by the table package.searchers. Each item in this table is a search function, that searches for the module in a particular way. By changing this table, we can change how require looks for a module. The following explanation is based on the default configuration for package.searchers.

​ 要查找加载器, require 由表 package.searchers 指导。此表中的每个项目都是一个搜索函数,它以特定方式搜索模块。通过更改此表,我们可以更改 require 查找模块的方式。以下说明基于 package.searchers 的默认配置。

First require queries package.preload[modname]. If it has a value, this value (which must 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.searchers).

​ 首先 require 查询 package.preload[modname] 。如果它具有值,则此值(必须是函数)是加载器。否则, require 使用存储在 package.path 中的路径搜索 Lua 加载器。如果也失败,它将使用存储在 package.cpath 中的路径搜索 C 加载器。如果也失败,它将尝试一个多合一加载器(请参阅 package.searchers )。

Once a loader is found, require calls the loader with two arguments: modname and an extra value, a loader data, also returned by the searcher. The loader data can be any value useful to the module; for the default searchers, it indicates where the loader was found. (For instance, if the loader came from a file, this extra value is the file path.) If the loader returns any non-nil value, require assigns the returned value to package.loaded[modname]. If the loader does not return a non-nil 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]. Besides that value, require also returns as a second result the loader data returned by the searcher, which indicates how require found the module.

​ 找到加载器后, require 会使用两个参数调用加载器: modname 和一个额外值,即加载器数据,也由搜索器返回。加载器数据可以是任何对模块有用的值;对于默认搜索器,它指示找到加载器的位置。(例如,如果加载器来自文件,此额外值就是文件路径。)如果加载器返回任何非 nil 值, require 会将返回的值分配给 package.loaded[modname] 。如果加载器未返回非 nil 值且未将任何值分配给 package.loaded[modname] ,则 require 会将 true 分配给此条目。无论哪种情况, require 都会返回 package.loaded[modname] 的最终值。除了该值之外, require 还将搜索器返回的加载器数据作为第二个结果返回,该数据指示 require 如何找到该模块。

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

​ 如果在加载或运行模块时出现任何错误,或者如果它找不到该模块的任何加载器,则 require 会引发错误。

package.config

A string describing some compile-time configurations for packages. This string is a sequence of lines:

​ 一个字符串,描述包的一些编译时配置。此字符串是一系列行:

  • The first line is the directory separator string. Default is ‘\’ for Windows and ‘/’ for all other systems. 第一行是目录分隔符字符串。对于 Windows,默认值为“ \ ”,对于所有其他系统,默认值为“ / ”。
  • The second line is the character that separates templates in a path. Default is ‘;’. 第二行是路径中分隔模板的字符。默认是“ ; ”。
  • The third line is the string that marks the substitution points in a template. Default is ‘?’. 第三行是标记模板中替换点的字符串。默认是“ ? ”。
  • The fourth line is a string that, in a path in Windows, is replaced by the executable’s directory. Default is ‘!’. 第四行是字符串,在 Windows 中的路径中,它被可执行文件的目录替换。默认是“ ! ”。
  • The fifth line is a mark to ignore all text after it when building the luaopen_ function name. Default is ‘-’. 第五行是标记,在构建 luaopen_ 函数名称时忽略其后的所有文本。默认是“ - ”。

package.cpath

A string with the path used by require to search for a C loader.

​ 一个字符串, require 用于搜索 C 加载器的路径。

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

​ Lua 以初始化 Lua 路径 package.path 的方式初始化 C 路径 package.cpath ,使用环境变量 LUA_CPATH_5_4 或环境变量 LUA_CPATH ,或在 luaconf.h 中定义的默认路径。

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.

require 用于控制哪些模块已加载的表。当您需要模块 modnamepackage.loaded[modname] 不为 false 时, require 仅返回存储在那里的值。

This variable is only a reference to the real table; assignments to this variable do not change the table used by require. The real table is stored in the C registry (see §4.3), indexed by the key LUA_LOADED_TABLE, a string.

​ 此变量仅是对真实表的引用;对该变量的赋值不会更改 require 使用的表。真实表存储在 C 注册表(参见§4.3)中,其索引为键 LUA_LOADED_TABLE ,一个字符串。

package.loadlib (libname, funcname)

Dynamically links the host program with the C library libname.

​ 动态地将宿主程序与 C 库 libname 链接。

If funcname is “*”, then it only links with the library, making the symbols exported by the library available to other dynamically linked libraries. Otherwise, it looks for a function funcname inside the library and returns this function as a C function. So, funcname must follow the lua_CFunction prototype (see lua_CFunction).

​ 如果 funcname 为“ * ”,则它只与库链接,使库导出的符号可供其他动态链接库使用。否则,它将在库内查找函数 funcname 并将此函数作为 C 函数返回。因此, funcname 必须遵循 lua_CFunction 原型(请参阅 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 an extension. funcname must be the exact name exported by the C library (which may depend on the C compiler and linker used).

​ 这是一个底层函数。它完全绕过了包和模块系统。与 require 不同,它不执行任何路径搜索,也不会自动添加扩展名。 libname 必须是 C 库的完整文件名,包括路径和扩展名(如果需要)。 funcname 必须是 C 库导出的确切名称(可能取决于所使用的 C 编译器和链接器)。

This functionality is not supported by ISO 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).

​ ISO C 不支持此功能。因此,它仅在某些平台(Windows、Linux、Mac OS X、Solaris、BSD 以及支持 dlfcn 标准的其他 Unix 系统)上可用。

This function is inherently insecure, as it allows Lua to call any function in any readable dynamic library in the system. (Lua calls any function assuming the function has a proper prototype and respects a proper protocol (see lua_CFunction). Therefore, calling an arbitrary function in an arbitrary dynamic library more often than not results in an access violation.)

​ 此函数本质上不安全,因为它允许 Lua 调用系统中任何可读动态库中的任何函数。(Lua 调用任何函数时都假设该函数具有正确的原型并遵守正确的协议(请参阅 lua_CFunction )。因此,在任意动态库中调用任意函数通常会导致访问冲突。)

package.path

A string with the path used by require to search for a Lua loader.

​ Lua 加载器用于搜索的路径的字符串。

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

​ 在启动时,如果未定义这些环境变量,Lua 会使用环境变量 LUA_PATH_5_4 或环境变量 LUA_PATH 的值或 luaconf.h 中定义的默认路径来初始化此变量。环境变量值中的“ ;; ”将替换为默认路径。

package.preload

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

​ 用于存储特定模块的加载器的表(请参阅 require )。

This variable is only a reference to the real table; assignments to this variable do not change the table used by require. The real table is stored in the C registry (see §4.3), indexed by the key LUA_PRELOAD_TABLE, a string.

​ 此变量只是对实际表的引用;对该变量的赋值不会更改 require 使用的表。实际表存储在 C 注册表(请参阅 §4.3)中,其索引为键 LUA_PRELOAD_TABLE ,即字符串。

package.searchers

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

require 用于控制如何查找模块的表。

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 argument. If the searcher finds the module, it returns another function, the module loader, plus an extra value, a loader data, that will be passed to that loader and returned as a second result by require. If it cannot find the module, it returns a string explaining why (or nil if it has nothing to say).

​ 此表中的每个条目都是一个搜索器函数。在查找模块时, require 按升序调用这些搜索器,并以模块名称(提供给 require 的参数)作为其唯一参数。如果搜索器找到模块,它将返回另一个函数(模块加载器)以及一个额外值(加载器数据),该值将传递给该加载器,并由 require 作为第二个结果返回。如果它找不到模块,它将返回一个字符串来解释原因(或在它无话可说时返回 nil)。

Lua initializes this table with four searcher functions.

​ Lua 使用四个搜索器函数初始化此表。

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

​ 第一个搜索器只是在 package.preload 表中查找加载器。

The second searcher looks for a loader as a Lua library, using the path stored at package.path. The search is done as described in function package.searchpath.

​ 第二个搜索器使用存储在 package.path 中的路径,将加载器作为 Lua 库进行查找。搜索按照函数 package.searchpath 中的描述进行。

The third searcher looks for a loader as a C library, using the path given by the variable package.cpath. Again, the search is done as described in function package.searchpath. For instance, if the C path is the string

​ 第三个搜索器使用变量 package.cpath 给出的路径,将加载器作为 C 库进行查找。同样,搜索按照函数 package.searchpath 中的描述进行。例如,如果 C 路径是字符串

     "./?.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 suffix after (and including) the first hyphen is removed. For instance, if the module name is a.b.c-v2.1, the function name will be luaopen_a_b_c.

​ 模块 foo 的搜索器将尝试按此顺序打开文件 ./foo.so./foo.dll/usr/local/foo/init.so 。找到 C 库后,此搜索器首先使用动态链接工具将应用程序与库链接。然后,它尝试在库中查找要作为加载器使用的 C 函数。此 C 函数的名称是字符串“ luaopen_ ”,连接模块名称的副本,其中每个点都替换为下划线。此外,如果模块名称带有连字符,则会删除其后缀(包括)第一个连字符。例如,如果模块名称是 a.b.c-v2.1 ,则函数名称将是 luaopen_a_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.

​ 第四个搜索器尝试一个多合一加载器。它在 C 路径中搜索给定模块的根名称的库。例如,在需要 a.b.c 时,它将搜索 a 的 C 库。如果找到,它将在其中查找子模块的 open 函数;在我们的示例中,那就是 luaopen_a_b_c 。借助此工具,一个包可以将多个 C 子模块打包到一个库中,每个子模块都保留其原始的 open 函数。

All searchers except the first one (preload) return as the extra value the file path where the module was found, as returned by package.searchpath. The first searcher always returns the string “:preload:”.

​ 除第一个搜索器(预加载)外,所有搜索器都将模块找到的文件路径作为额外值返回,该路径由 package.searchpath 返回。第一个搜索器始终返回字符串“ :preload: ”。

Searchers should raise no errors and have no side effects in Lua. (They may have side effects in C, for instance by linking the application with a library.)

​ 搜索器不应引发错误,并且在 Lua 中没有任何副作用。(它们可能在 C 中产生副作用,例如通过将应用程序与库链接。)

package.searchpath (name, path [, sep [, rep]])

Searches for the given name in the given path.

​ 在给定的 path 中搜索给定的 name

A path is a string containing a sequence of templates separated by semicolons. For each template, the function replaces each interrogation mark (if any) in the template with a copy of name wherein all occurrences of sep (a dot, by default) were replaced by rep (the system’s directory separator, by default), and then tries to open the resulting file name.

​ 路径是一个字符串,其中包含由分号分隔的一系列模板。对于每个模板,该函数用 name 的副本替换模板中的每个问号(如果有),其中 sep (默认情况下为点)的所有出现都被 rep (默认情况下为系统的目录分隔符)替换,然后尝试打开结果文件名。

For instance, if the path is the string

​ 例如,如果路径是字符串

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

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

​ 则对名称 foo.a 的搜索将尝试按此顺序打开文件 ./foo/a.lua./foo/a.lc/usr/local/foo/a/init.lua

Returns the resulting name of the first file that it can open in read mode (after closing the file), or fail plus an error message if none succeeds. (This error message lists all file names it tried to open.)

​ 返回第一个可以打开的文件(关闭文件后)的结果名称,或者如果没有任何文件成功,则返回失败和错误消息。(此错误消息列出它尝试打开的所有文件名。)

6.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.

​ 此库提供用于字符串操作的通用函数,例如查找和提取子字符串以及模式匹配。在 Lua 中对字符串进行索引时,第一个字符位于位置 1(不在位置 0,如在 C 中)。允许索引为负数,并将其解释为从字符串末尾向后索引。因此,最后一个字符位于位置 -1,依此类推。

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).

​ 字符串库在其内部表 string 中提供所有函数。它还为字符串设置元表,其中 __index 字段指向 string 表。因此,您可以在面向对象样式中使用字符串函数。例如,可以将 string.byte(s,i) 写成 s:byte(i)

The string library assumes one-byte character encodings.

​ 字符串库假定使用单字节字符编码。

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

Returns the internal numeric 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. These indices are corrected following the same rules of function string.sub. 返回字符 s[i]s[i+1] 、…、 s[j] 的内部数字代码。 i 的默认值为 1; j 的默认值为 i 。这些索引按照函数 string.sub 的相同规则进行更正。

Numeric 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 numeric code equal to its corresponding argument. 接收零个或多个整数。返回一个字符串,其长度等于参数的数量,其中每个字符的内部数字代码等于其对应的参数。

Numeric codes are not necessarily portable across platforms.

​ 数字代码不一定可以在不同平台之间移植。

string.dump (function [, strip])

Returns a string containing a binary representation (a binary chunk) of the given function, so that a later load on this string returns a copy of the function (but with new upvalues). If strip is a true value, the binary representation may not include all debug information about the function, to save space.

​ 返回一个包含给定函数的二进制表示(一个二进制块)的字符串,以便以后对该字符串执行 load 可返回该函数的副本(但具有新的向上值)。如果 strip 为真值,则二进制表示可能不包含有关该函数的所有调试信息,以节省空间。

Functions with upvalues have only their number of upvalues saved. When (re)loaded, those upvalues receive fresh instances. (See the load function for details about how these upvalues are initialized. You can use the debug library to serialize and reload the upvalues of a function in a way adequate to your needs.)

​ 带有 upvalue 的函数只保存其 upvalue 的数量。重新加载时,这些 upvalue 会收到新的实例。(有关如何初始化这些 upvalue 的详细信息,请参阅 load 函数。您可以使用 debug 库以适合您需求的方式序列化和重新加载函数的 upvalue。)

string.find (s, pattern [, init [, plain]])

Looks for the first match of pattern (see §6.4.1) in the string s. If it finds a match, then find returns the indices of s where this occurrence starts and ends; otherwise, it returns fail. A third, optional numeric argument init specifies where to start the search; its default value is 1 and can be negative. A true as a fourth, optional argument plain turns off the pattern matching facilities, so the function does a plain “find substring” operation, with no characters in pattern being considered magic.

​ 在字符串 s 中查找 pattern 的第一个匹配项(请参阅 §6.4.1)。如果找到匹配项,则 find 返回此匹配项开始和结束的 s 索引;否则,返回失败。第三个可选数字参数 init 指定从哪里开始搜索;其默认值为 1,可以为负数。第四个可选参数 plain 为 true 时,关闭模式匹配功能,因此该函数执行简单的“查找子字符串”操作,而不将 pattern 中的任何字符视为魔术字符。

If the pattern has captures, then in a successful match the captured values are also returned, after the two indices.

​ 如果模式有捕获,则在成功匹配时,捕获的值也会在两个索引之后返回。

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 ISO C function sprintf. The only differences are that the conversion specifiers and modifiers F, n, *, h, L, and l are not supported and that there is an extra specifier, q. Both width and precision, when present, are limited to two digits.

​ 返回一个格式化版本的可变数量的参数,这些参数遵循其第一个参数中给出的描述,该参数必须是一个字符串。格式字符串遵循与 ISO C 函数 sprintf 相同的规则。唯一的区别是转换说明符和修饰符 Fn*hLl 不受支持,并且有一个额外的说明符 q 。当存在时,宽度和精度都限制为两位数。

The specifier q formats booleans, nil, numbers, and strings in a way that the result is a valid constant in Lua source code. Booleans and nil are written in the obvious way (true, false, nil). Floats are written in hexadecimal, to preserve full precision. A string is written between double quotes, using escape sequences when necessary to ensure that it can safely be read back by the Lua interpreter. For instance, the call

​ 说明符 q 以结果为 Lua 源代码中有效常量的方式格式化布尔值、nil、数字和字符串。布尔值和 nil 以明显的方式编写( truefalsenil )。浮点数以十六进制形式编写,以保持完全精度。字符串用双引号括起来,必要时使用转义序列以确保 Lua 解释器可以安全地重新读取它。例如,调用

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

may produce the string:

​ 可能会产生字符串:

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

This specifier does not support modifiers (flags, width, precision).

​ 此说明符不支持修饰符(标志、宽度、精度)。

The conversion specifiers A, a, E, e, f, G, and g all expect a number as argument. The specifiers c, d, i, o, u, X, and x expect an integer. When Lua is compiled with a C89 compiler, the specifiers A and a (hexadecimal floats) do not support modifiers.

​ 转换说明符 AaEefGg 都期望一个数字作为参数。说明符 cdiouXx 期望一个整型。当 Lua 使用 C89 编译器编译时,说明符 Aa (十六进制浮点数)不支持修饰符。

The specifier s expects a string; if its argument is not a string, it is converted to one following the same rules of tostring. If the specifier has any modifier, the corresponding string argument should not contain embedded zeros.

​ 说明符 s 期望一个字符串;如果其参数不是字符串,则按照 tostring 的相同规则将其转换为字符串。如果说明符有任何修饰符,则相应的字符串参数不应包含嵌入式零。

The specifier p formats the pointer returned by lua_topointer. That gives a unique string identifier for tables, userdata, threads, strings, and functions. For other values (numbers, nil, booleans), this specifier results in a string representing the pointer NULL.

​ 说明符 p 会格式化 lua_topointer 返回的指针。这会为表、用户数据、线程、字符串和函数提供一个唯一的字符串标识符。对于其他值(数字、nil、布尔值),此说明符会生成一个表示指针 NULL 的字符串。

string.gmatch (s, pattern [, init])

Returns an iterator function that, each time it is called, returns the next captures from pattern (see §6.4.1) over the string s. If pattern specifies no captures, then the whole match is produced in each call. A third, optional numeric argument init specifies where to start the search; its default value is 1 and can be negative. 返回一个迭代器函数,每次调用时,都会返回从字符串 s 中捕获的下一个内容(参见 §6.4.1)。如果 pattern 没有指定任何捕获,那么每次调用都会生成整个匹配项。第三个可选数字参数 init 指定从哪里开始搜索;其默认值为 1,可以为负数。

As an example, the following loop will iterate over all the words from string s, printing one per line:

​ 例如,以下循环将迭代字符串 s 中的所有单词,每行打印一个单词:

     s = "hello world from Lua"
     for w in string.gmatch(s, "%a+") do
       print(w)
     end
s = "hello world from Lua"
for w in string.gmatch(s, "%a+") do
print(w)
end

The next example collects all pairs key=value from the given string into a table:

​ 下一个示例将给定字符串中的所有对 key=value 收集到一个表中:

     t = {}
     s = "from=world, to=Lua"
     for k, v in string.gmatch(s, "(%w+)=(%w+)") do
       t[k] = v
     end
t = {}
s = "from=world, to=Lua"
for k, v in string.gmatch(s, "(%w+)=(%w+)") do
t[k] = v
结束

For this function, a caret ‘^’ at the start of a pattern does not work as an anchor, as this would prevent the iteration.

​ 对于此函数,模式开头处的插入符号“ ^ ”不能用作锚点,因为这会阻止迭代。

string.gsub (s, pattern, repl [, n])

Returns a copy of s in which all (or the first n, if given) occurrences of the pattern (see §6.4.1) have been replaced by a replacement string specified by repl, which can be a string, a table, or a function. gsub also returns, as its second value, the total number of matches that occurred. The name gsub comes from Global SUBstitution. 返回 s 的副本,其中所有(或第一个 n ,如果给出)出现的 pattern (参见 §6.4.1)已被 repl 指定的替换字符串替换,它可以是字符串、表或函数。 gsub 还返回匹配发生的总数作为其第二个值。名称 gsub 来自全局替换。

If repl is a string, then its value is used for replacement. The character % works as an escape character: any sequence in repl of the form %*d*, with d between 1 and 9, stands for the value of the d-th captured substring; the sequence %0 stands for the whole match; the sequence %% stands for a single %.

​ 如果 repl 是字符串,则其值用于替换。字符 % 用作转义字符: repl 中的任何形式为 %*d* 的序列,其中 d 在 1 到 9 之间,代表第 d 个捕获子字符串的值;序列 %0 代表整个匹配项;序列 %% 代表单个 %

If repl is a table, then the table is queried for every match, using the first capture as the key.

​ 如果 repl 是表,则使用第一个捕获作为键,对每个匹配项查询表。

If repl is a function, then this function is called every time a match occurs, with all captured substrings passed as arguments, in order.

​ 如果 repl 是函数,则每次发生匹配时都会调用此函数,并将所有捕获的子字符串按顺序作为参数传递。

In any case, if the pattern specifies no captures, then it behaves as if the whole pattern was inside a capture.

​ 无论如何,如果模式未指定捕获,则其行为就像整个模式位于捕获中一样。

If the value returned by the table query or by the function call is a string or a number, then it is used as the replacement string; otherwise, if it is false or nil, then there is no replacement (that is, the original match is kept in the string).

​ 如果表查询或函数调用返回的值是字符串或数字,则将其用作替换字符串;否则,如果为 false 或 nil,则没有替换(即,原始匹配项保留在字符串中)。

Here are some examples:

​ 以下是一些示例:

     x = string.gsub("hello world", "(%w+)", "%1 %1")
     --> x="hello hello world world"
     
     x = string.gsub("hello world", "%w+", "%0 %0", 1)
     --> x="hello hello world"
     
     x = string.gsub("hello world from Lua", "(%w+)%s*(%w+)", "%2 %1")
     --> x="world hello Lua from"
     
     x = string.gsub("home = $HOME, user = $USER", "%$(%w+)", os.getenv)
     --> x="home = /home/roberto, user = roberto"
     
     x = string.gsub("4+5 = $return 4+5$", "%$(.-)%$", function (s)
           return load(s)()
         end)
     --> x="4+5 = 9"
     
     local t = {name="lua", version="5.4"}
     x = string.gsub("$name-$version.tar.gz", "%$(%w+)", t)
     --> x="lua-5.4.tar.gz"
x = string.gsub("hello world", "(%w+)", "%1 %1")
--> x="hello hello world world"

x = string.gsub("hello world", "%w+", "%0 %0", 1)
--> x="hello hello world"

x = string.gsub("hello world from Lua", "(%w+)%s*(%w+)", "%2 %1")
--> x="world hello Lua from"

x = string.gsub("home = $HOME, user = $USER", "%$(%w+)", os.getenv)
--> x="home = /home/roberto, user = roberto"

x = string.gsub("4+5 = $return 4+5$", "%$(.-)%$", function (s)
return load(s)()
end)
--> x="4+5 = 9"

local t = {name="lua", version="5.4"}
x = string.gsub("$name-$version.tar.gz", "%$(%w+)", t)
--> x="lua-5.4.tar.gz"

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.

​ 接收一个字符串并返回其长度。空字符串 "" 的长度为 0。嵌入的零会被计数,因此 "a\000bc\000" 的长度为 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.match (s, pattern [, init])

Looks for the first match of the pattern (see §6.4.1) in the string s. If it finds one, then match returns the captures from the pattern; otherwise it returns fail. If pattern specifies no captures, then the whole match is returned. A third, optional numeric argument init specifies where to start the search; its default value is 1 and can be negative.

​ 在字符串 s 中查找 pattern 的第一个匹配项(请参阅 §6.4.1)。如果找到一个,则 match 返回从该模式捕获的内容;否则返回失败。如果 pattern 未指定任何捕获内容,则返回整个匹配项。第三个可选数字参数 init 指定从哪里开始搜索;其默认值为 1,可以为负数。

string.pack (fmt, v1, v2, ···)

Returns a binary string containing the values v1, v2, etc. serialized in binary form (packed) according to the format string fmt (see §6.4.2).

​ 返回一个二进制字符串,其中包含按照格式字符串 fmt (请参阅 §6.4.2)以二进制形式(打包)序列化的值 v1v2 等。

string.packsize (fmt)

Returns the length of a string resulting from string.pack with the given format. The format string cannot have the variable-length options ‘s’ or ‘z’ (see §6.4.2).

​ 返回由 string.pack 生成的字符串的长度,其中包含给定的格式。格式字符串不能包含可变长度选项“ s ”或“ z ”(请参阅 §6.4.2)。

string.rep (s, n [, sep])

Returns a string that is the concatenation of n copies of the string s separated by the string sep. The default value for sep is the empty string (that is, no separator). Returns the empty string if n is not positive.

​ 返回一个字符串,该字符串是字符串 sn 个副本的连接,这些副本由字符串 sep 分隔。对于 sep ,默认值为一个空字符串(即没有分隔符)。如果 n 不是正数,则返回一个空字符串。

(Note that it is very easy to exhaust the memory of your machine with a single call to this function.)

​ (请注意,只需调用此函数一次,就很容易耗尽计算机的内存。)

string.reverse (s)

Returns a string that is the string s reversed.

​ 返回一个字符串,该字符串是字符串 s 的反转。

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) (for a positive i) returns a suffix of s with length i.

​ 返回从 s 中的 i 开始并持续到 j 的子字符串; ij 可以为负数。如果 j 不存在,则假定它等于 -1(与字符串长度相同)。特别是,调用 string.sub(s,1,j) 返回长度为 js 的前缀,而 string.sub(s, -i) (对于正数 i )返回长度为 is 的后缀。

If, after the translation of negative indices, i is less than 1, it is corrected to 1. If j is greater than the string length, it is corrected to that length. If, after these corrections, i is greater than j, the function returns the empty string.

​ 如果在转换负数索引后, i 小于 1,则将其更正为 1。如果 j 大于字符串长度,则将其更正为该长度。如果在这些更正之后, i 大于 j ,则该函数返回空字符串。

string.unpack (fmt, s [, pos])

Returns the values packed in string s (see string.pack) according to the format string fmt (see §6.4.2). An optional pos marks where to start reading in s (default is 1). After the read values, this function also returns the index of the first unread byte in s.

​ 根据格式字符串 fmt (参见 §6.4.2)返回字符串 s 中打包的值(参见 string.pack )。可选的 pos 标记在 s 中开始读取的位置(默认为 1)。在读取值之后,此函数还会返回 s 中第一个未读字节的索引。

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.

​ 接收一个字符串并返回一个副本,其中所有小写字母都已更改为大写字母。所有其他字符保持不变。小写字母的定义取决于当前语言环境。

6.4.1 – Patterns 模式

Patterns in Lua are described by regular strings, which are interpreted as patterns by the pattern-matching functions string.find, string.gmatch, string.gsub, and string.match. This section describes the syntax and the meaning (that is, what they match) of these strings.

​ Lua 中的模式由正则字符串描述,模式匹配函数 string.findstring.gmatchstring.gsubstring.match 将其解释为模式。本节介绍这些字符串的语法和含义(即它们匹配的内容)。

Character Class: 字符类:

A character class is used to represent a set of characters. The following combinations are allowed in describing a character class:

​ 字符类用于表示一组字符。在描述字符类时允许使用以下组合:

  • *x*: (where x is not one of the magic characters ^$()%.[]*+-?) represents the character x itself. x:(其中 x 不是魔术字符 ^$()%.[]*+-? 之一)表示字符 x 本身。

  • .: (a dot) represents all characters. . :(一个点)表示所有字符。

  • %a: represents all letters. %a :表示所有字母。

  • %c: represents all control characters. %c :表示所有控制字符。

  • %d: represents all digits. %d :表示所有数字。

  • %g: represents all printable characters except space. %g :表示除空格外的所有可打印字符。

  • %l: represents all lowercase letters. %l :表示所有小写字母。

  • %p: represents all punctuation characters. %p :表示所有标点符号。

  • %s: represents all space characters. %s :表示所有空格字符。

  • %u: represents all uppercase letters. %u :表示所有大写字母。

  • %w: represents all alphanumeric characters. %w :表示所有字母数字字符。

  • %x: represents all hexadecimal digits. %x :表示所有十六进制数字。

  • %\*x\*: (where x is any non-alphanumeric character) represents the character x. This is the standard way to escape the magic characters. Any non-alphanumeric character (including all punctuation characters, even the non-magical) can be preceded by a ‘%’ to represent itself in a pattern. %*x* :(其中 x 是任何非字母数字字符)表示字符 x。这是转义魔术字符的标准方法。任何非字母数字字符(包括所有标点符号,即使是非魔术的)都可以前置“ % ”来表示其自身在模式中。

  • [*set*]:

    represents the class which is the union of all characters in

    set

    . A range of characters can be specified by separating the end characters of the range, in ascending order, with a '

    -
    

    ‘. All classes

    %
    

    x

    described above can also be used as components in

    set

    . All other characters in

    set

    represent themselves. For example,

    [%w_]
    

    (or

    [_%w]
    

    ) represents all alphanumeric characters plus the underscore,

    [0-7]
    

    represents the octal digits, and

    [0-7%l%-]
    

    represents the octal digits plus the lowercase letters plus the '

    -
    

    ’ character.

    [*set*] :表示类,该类是集合中所有字符的并集。可以通过按升序用“ - ”分隔范围的结束字符来指定一系列字符。上面描述的所有类 % x 也可用作集合中的组件。集合中的所有其他字符都表示它们自身。例如, [%w_] (或 [_%w] )表示所有字母数字字符加上下划线, [0-7] 表示八进制数字, [0-7%l%-] 表示八进制数字加上小写字母加上“ - ”字符。

    You can put a closing square bracket in a set by positioning it as the first character in the set. You can put a hyphen in a set by positioning it as the first or the last character in the set. (You can also use an escape for both cases.)

    ​ 您可以通过将闭合方括号定位为集合中的第一个字符来将其放入集合中。您可以通过将连字符定位为集合中的第一个或最后一个字符来将其放入集合中。(您也可以在这两种情况下使用转义。)

    The interaction between ranges and classes is not defined. Therefore, patterns like [%a-z] or [a-%%] have no meaning.

    ​ 范围和类之间的交互未定义。因此,诸如 [%a-z][a-%%] 之类的模式没有任何意义。

  • [^\*set\*]: represents the complement of set, where set is interpreted as above. [^*set*] :表示集合的补集,其中集合解释如上。

For all classes represented by single letters (%a, %c, etc.), the corresponding uppercase letter represents the complement of the class. For instance, %S represents all non-space characters.

​ 对于由单个字母表示的所有类( %a%c 等),相应的字母大写表示该类的补集。例如, %S 表示所有非空格字符。

The definitions of letter, space, and other character groups depend on the current locale. In particular, the class [a-z] may not be equivalent to %l.

​ 字母、空格和其他字符组的定义取决于当前区域设置。特别是,类 [a-z] 可能不等于 %l

Pattern Item: 模式项:

A pattern item can be

​ 模式项可以是

  • a single character class, which matches any single character in the class; 单个字符类,它匹配类中的任何单个字符;
  • a single character class followed by ‘*’, which matches sequences of zero or more characters in the class. These repetition items will always match the longest possible sequence; 单个字符类后跟“ * ”,它匹配类中零个或多个字符的序列。这些重复项将始终匹配最长的可能序列;
  • a single character class followed by ‘+’, which matches sequences of one or more characters in the class. These repetition items will always match the longest possible sequence; 单个字符类后跟“ + ”,它匹配类中一个或多个字符的序列。这些重复项将始终匹配最长的可能序列;
  • a single character class followed by ‘-’, which also matches sequences of zero or more characters in the class. Unlike ‘*’, these repetition items will always match the shortest possible sequence; 单个字符类后跟 ’ - ‘,它也匹配类中零个或多个字符的序列。与 ’ * ’ 不同,这些重复项将始终匹配最短可能的序列;
  • a single character class followed by ‘?’, which matches zero or one occurrence of a character in the class. It always matches one occurrence if possible; 单个字符类后跟 ’ ? ‘,它匹配类中一个字符的零次或一次出现。如果可能,它始终匹配一次出现;
  • %*n*, for n between 1 and 9; such item matches a substring equal to the n-th captured string (see below); %*n* ,n 在 1 到 9 之间;此类项匹配等于第 n 个捕获字符串的子字符串(见下文);
  • %b*xy*, where x and y are two distinct characters; such item matches strings that start with x, end with y, and where the x and y are balanced. This means that, if one reads the string from left to right, counting +1 for an x and -1 for a y, the ending y is the first y where the count reaches 0. For instance, the item %b() matches expressions with balanced parentheses. %b*xy* ,其中 x 和 y 是两个不同的字符;此类项匹配以 x 开头、以 y 结尾且 x 和 y 平衡的字符串。这意味着,如果从左到右读取字符串,对 x 计数 +1,对 y 计数 -1,则结束 y 是计数达到 0 的第一个 y。例如,项 %b() 匹配带平衡括号的表达式。
  • %f[*set*], a frontier pattern; such item matches an empty string at any position such that the next character belongs to set and the previous character does not belong to set. The set set is interpreted as previously described. The beginning and the end of the subject are handled as if they were the character ‘\0’. %f[*set*] ,边沿模式;此类项目匹配任何位置的空字符串,使得下一个字符属于集合,而前一个字符不属于集合。集合 set 的解释如前所述。主题的开头和结尾被视为字符“ \0 ”。

Pattern: 模式:

A pattern is a sequence of pattern items. A caret ‘^’ at the beginning of a pattern anchors the match at the beginning of the subject string. A ‘$’ at the end of a pattern anchors the match at the end of the subject string. At other positions, ‘^’ and ‘$’ have no special meaning and represent themselves.

​ 模式是模式项的序列。模式开头处的脱字符“ ^ ”将匹配锚定在主题字符串的开头。模式末尾处的“ $ ”将匹配锚定在主题字符串的末尾。在其他位置,“ ^ ”和“ $ ”没有特殊含义,表示它们自己。

Captures: 捕获:

A pattern can contain sub-patterns enclosed in parentheses; they describe captures. When a match succeeds, the substrings of the subject string that match captures are stored (captured) for future use. Captures are numbered according to their left parentheses. For instance, in the pattern "(a*(.)%w(%s*))", the part of the string matching "a*(.)%w(%s*)" is stored as the first capture, and therefore has number 1; the character matching “.” is captured with number 2, and the part matching “%s*” has number 3.

​ 模式可以包含用括号括起来的子模式;它们描述捕获。当匹配成功时,与捕获匹配的主题字符串的子字符串被存储(捕获)以备将来使用。捕获根据其左括号进行编号。例如,在模式 "(a*(.)%w(%s*))" 中,与 "a*(.)%w(%s*)" 匹配的字符串部分存储为第一个捕获,因此编号为 1;与 " . " 匹配的字符以编号 2 捕获,与 " %s* " 匹配的部分编号为 3。

As a special case, the capture () captures the current string position (a number). For instance, if we apply the pattern "()aa()" on the string "flaaap", there will be two captures: 3 and 5.

​ 作为特例,捕获 () 捕获当前字符串位置(一个数字)。例如,如果我们将模式 "()aa()" 应用于字符串 "flaaap" ,将有两个捕获:3 和 5。

Multiple matches: 多次匹配:

The function string.gsub and the iterator string.gmatch match multiple occurrences of the given pattern in the subject. For these functions, a new match is considered valid only if it ends at least one byte after the end of the previous match. In other words, the pattern machine never accepts the empty string as a match immediately after another match. As an example, consider the results of the following code:

​ 函数 string.gsub 和迭代器 string.gmatch 匹配主题中给定模式的多次出现。对于这些函数,只有在至少比前一个匹配的结尾多一个字节处结束时,才认为新匹配有效。换句话说,模式机器绝不会在另一个匹配之后立即接受空字符串作为匹配。例如,考虑以下代码的结果:

     > string.gsub("abc", "()a*()", print);
     --> 1   2
     --> 3   3
     --> 4   4
> string.gsub("abc", "()a*()", print);
--> 1   2
--> 3   3
--> 4   4

The second and third results come from Lua matching an empty string after ‘b’ and another one after ‘c’. Lua does not match an empty string after ‘a’, because it would end at the same position of the previous match.

​ 第二个和第三个结果来自 Lua 在“ b ”之后匹配一个空字符串,以及在“ c ”之后匹配另一个空字符串。Lua 不会在“ a ”之后匹配一个空字符串,因为它将在前一个匹配的相同位置结束。

6.4.2 – Format Strings for Pack and Unpack 用于打包和解包的格式字符串

The first argument to string.pack, string.packsize, and string.unpack is a format string, which describes the layout of the structure being created or read.

string.packstring.packsizestring.unpack 的第一个参数是格式字符串,它描述了正在创建或读取的结构的布局。

A format string is a sequence of conversion options. The conversion options are as follows:

​ 格式字符串是转换选项的序列。转换选项如下:

  • <: sets little endian < :设置小端序
  • >: sets big endian > :设置大端序
  • =: sets native endian = :设置本机端序
  • ![\*n\*]: sets maximum alignment to n (default is native alignment) ![*n*] :将最大对齐设置为 n (默认值为本机对齐)
  • b: a signed byte (char) b :一个有符号字节( char
  • B: an unsigned byte (char) B :一个无符号字节( char
  • h: a signed short (native size) h :一个有符号 short (本机大小)
  • H: an unsigned short (native size) H :一个无符号 short (本机大小)
  • l: a signed long (native size) l :一个有符号 long (本机大小)
  • L: an unsigned long (native size) L :一个无符号 long (本机大小)
  • j: a lua_Integer j :一个 lua_Integer
  • J: a lua_Unsigned J :一个 lua_Unsigned
  • T: a size_t (native size) T :一个 size_t (本机大小)
  • i[\*n\*]: a signed int with n bytes (default is native size) i[*n*] :带 n 字节的已签名 int (默认值为本机大小)
  • I[\*n\*]: an unsigned int with n bytes (default is native size) I[*n*] :带 n 字节的无符号 int (默认值为本机大小)
  • f: a float (native size) f :一个 float (本机大小)
  • d: a double (native size) d :一个 double (本机大小)
  • n: a lua_Number n :一个 lua_Number
  • c\*n\*: a fixed-sized string with n bytes c*n* :一个固定大小的字符串,带 n 字节
  • z: a zero-terminated string z :一个以零结尾的字符串
  • s[\*n\*]: a string preceded by its length coded as an unsigned integer with n bytes (default is a size_t) s[*n*] :一个字符串,其前缀是其长度,该长度编码为带 n 字节的无符号整数(默认值为 size_t
  • x: one byte of padding x :一个字节的填充
  • X\*op\*: an empty item that aligns according to option op (which is otherwise ignored) X*op* :一个空项目,根据选项 op 对齐(否则将忽略该选项)
  • ’: (space) ignored ’ ``’: (空格) 被忽略

(A “[*n*]” means an optional integral numeral.) Except for padding, spaces, and configurations (options “xX <=>!”), each option corresponds to an argument in string.pack or a result in string.unpack.

​ (“ [*n*] ”表示可选的整数。)除了填充、空格和配置(选项“ xX <=>! ”)之外,每个选项都对应于 string.pack 中的参数或 string.unpack 中的结果。

For options “!*n*”, “s*n*”, “i*n*”, and “I*n*”, n can be any integer between 1 and 16. All integral options check overflows; string.pack checks whether the given value fits in the given size; string.unpack checks whether the read value fits in a Lua integer. For the unsigned options, Lua integers are treated as unsigned values too.

​ 对于选项“ !*n* ”、“ s*n* ”、“ i*n* ”和“ I*n* ”, n 可以是 1 到 16 之间的任何整数。所有整数选项都会检查溢出; string.pack 检查给定值是否适合给定大小; string.unpack 检查读取的值是否适合 Lua 整数。对于无符号选项,Lua 整数也被视为无符号值。

Any format string starts as if prefixed by “!1=”, that is, with maximum alignment of 1 (no alignment) and native endianness.

​ 任何格式字符串都以“ !1= ”为前缀开始,即最大对齐方式为 1(无对齐方式)且为本机字节序。

Native endianness assumes that the whole system is either big or little endian. The packing functions will not emulate correctly the behavior of mixed-endian formats.

​ 本机字节序假定整个系统是大端或小端。打包函数不会正确模拟混合字节序格式的行为。

Alignment works as follows: For each option, the format gets extra padding until the data starts at an offset that is a multiple of the minimum between the option size and the maximum alignment; this minimum must be a power of 2. Options “c” and “z” are not aligned; option “s” follows the alignment of its starting integer.

​ 对齐方式的工作原理如下:对于每个选项,格式会获取额外的填充,直到数据从一个偏移量开始,该偏移量是选项大小和最大对齐之间的最小值的倍数;此最小值必须是 2 的幂。选项“ c ”和“ z ”未对齐;选项“ s ”遵循其起始整数的对齐方式。

All padding is filled with zeros by string.pack and ignored by string.unpack.

​ 所有填充都由 string.pack 填充为零,并由 string.unpack 忽略。

6.5 – UTF-8 Support 6.5 – UTF-8 支持

This library provides basic support for UTF-8 encoding. It provides all its functions inside the table utf8. This library does not provide any support for Unicode other than the handling of the encoding. Any operation that needs the meaning of a character, such as character classification, is outside its scope.

​ 此库提供对 UTF-8 编码的基本支持。它在表 utf8 中提供所有函数。此库不提供对 Unicode 的任何支持,除了处理编码之外。任何需要字符含义的操作(例如字符分类)都超出了其范围。

Unless stated otherwise, all functions that expect a byte position as a parameter assume that the given position is either the start of a byte sequence or one plus the length of the subject string. As in the string library, negative indices count from the end of the string.

​ 除非另有说明,否则所有将字节位置作为参数的函数都假定给定位置是字节序列的开头或主题字符串的长度加一。与字符串库一样,负索引从字符串末尾开始计数。

Functions that create byte sequences accept all values up to 0x7FFFFFFF, as defined in the original UTF-8 specification; that implies byte sequences of up to six bytes.

​ 创建字节序列的函数接受所有值,最高可达 0x7FFFFFFF ,如原始 UTF-8 规范中定义;这意味着字节序列最多可包含六个字节。

Functions that interpret byte sequences only accept valid sequences (well formed and not overlong). By default, they only accept byte sequences that result in valid Unicode code points, rejecting values greater than 10FFFF and surrogates. A boolean argument lax, when available, lifts these checks, so that all values up to 0x7FFFFFFF are accepted. (Not well formed and overlong sequences are still rejected.)

​ 解释字节序列的函数只接受有效序列(格式正确且不过长)。默认情况下,它们只接受生成有效 Unicode 代码点的字节序列,拒绝大于 10FFFF 和代理项的值。布尔参数 lax (如果可用)会取消这些检查,以便接受所有值,最高可达 0x7FFFFFFF 。(格式不正确和过长的序列仍然会被拒绝。)

utf8.char (···)

Receives zero or more integers, converts each one to its corresponding UTF-8 byte sequence and returns a string with the concatenation of all these sequences.

​ 接收零个或多个整数,将每个整数转换为其对应的 UTF-8 字节序列,并返回一个包含所有这些序列连接而成的字符串。

utf8.charpattern

The pattern (a string, not a function) “[\0-\x7F\xC2-\xFD][\x80-\xBF]*” (see §6.4.1), which matches exactly one UTF-8 byte sequence, assuming that the subject is a valid UTF-8 string.

​ 模式(一个字符串,不是一个函数)“ [\0-\x7F\xC2-\xFD][\x80-\xBF]* ”(参见 §6.4.1),它完全匹配一个 UTF-8 字节序列,假设主题是一个有效的 UTF-8 字符串。

utf8.codes (s [, lax])

Returns values so that the construction

​ 返回的值使得构造 for p, c in utf8.codes(s) do body end

     for p, c in utf8.codes(s) do body end

will iterate over all UTF-8 characters in string s, with p being the position (in bytes) and c the code point of each character. It raises an error if it meets any invalid byte sequence.

​ 将迭代字符串 s 中的所有 UTF-8 字符,其中 p 是位置(以字节为单位), c 是每个字符的代码点。如果遇到任何无效的字节序列,它会引发错误。

utf8.codepoint (s [, i [, j [, lax]]])

Returns the code points (as integers) from all characters in s that start between byte position i and j (both included). The default for i is 1 and for j is i. It raises an error if it meets any invalid byte sequence.

​ 返回从 s 中所有字符开始的代码点(作为整数),这些字符的字节位置介于 ij 之间(包括两者)。 i 的默认值为 1, j 的默认值为 i 。如果遇到任何无效的字节序列,它会引发错误。

utf8.len (s [, i [, j [, lax]]])

Returns the number of UTF-8 characters in string s that start between positions i and j (both inclusive). The default for i is 1 and for j is -1. If it finds any invalid byte sequence, returns fail plus the position of the first invalid byte.

​ 返回字符串 s 中从位置 ij (包括两者)开始的 UTF-8 字符数。对于 i 的默认值为 1,对于 j 的默认值为 -1。如果找到任何无效的字节序列,则返回失败以及第一个无效字节的位置。

utf8.offset (s, n [, i])

Returns the position (in bytes) where the encoding of the n-th character of s (counting from position i) starts. A negative n gets characters before position i. The default for i is 1 when n is non-negative and #s + 1 otherwise, so that utf8.offset(s, -n) gets the offset of the n-th character from the end of the string. If the specified character is neither in the subject nor right after its end, the function returns fail.

​ 返回 s 的第 n 个字符(从位置 i 开始计数)的编码开始的位置(以字节为单位)。负 n 获取位置 i 之前字符。当 n 为非负数时, i 的默认值为 1,否则为 #s + 1 ,以便 utf8.offset(s, -n) 获取字符串末尾第 n 个字符的偏移量。如果指定字符既不在主题中也不在其末尾之后,则该函数返回失败。

As a special case, when n is 0 the function returns the start of the encoding of the character that contains the i-th byte of s.

​ 作为特例,当 n 为 0 时,该函数返回包含 s 的第 i 个字节的字符的编码的开始。

This function assumes that s is a valid UTF-8 string.

​ 此函数假定 s 是有效的 UTF-8 字符串。

6.6 – Table Manipulation 表格操作

This library provides generic functions for table manipulation. It provides all its functions inside the table table.

​ 此库提供用于表格操作的通用函数。它在表格 table 中提供所有函数。

Remember that, whenever an operation needs the length of a table, all caveats about the length operator apply (see §3.4.7). All functions ignore non-numeric keys in the tables given as arguments.

​ 请记住,每当操作需要表格长度时,都会应用有关长度运算符的所有注意事项(请参阅 §3.4.7)。所有函数都会忽略作为参数给出的表格中的非数字键。

table.concat (list [, sep [, i [, j]]])

Given a list where all elements are strings or numbers, returns the string list[i]..sep..list[i+1] ··· sep..list[j]. The default value for sep is the empty string, the default for i is 1, and the default for j is #list. If i is greater than j, returns the empty string.

​ 给定一个列表,其中所有元素都是字符串或数字,返回字符串 list[i]..sep..list[i+1] ··· sep..list[j]sep 的默认值为一个空字符串, i 的默认值为 1, j 的默认值为 #list 。如果 i 大于 j ,则返回一个空字符串。

table.insert (list, [pos,] value)

Inserts element value at position pos in list, shifting up the elements list[pos], list[pos+1], ···, list[#list]. The default value for pos is #list+1, so that a call table.insert(t,x) inserts x at the end of the list t.

​ 在 list 中的 pos 位置插入元素 value ,将元素 list[pos], list[pos+1], ···, list[#list] 向上移动。 pos 的默认值为 #list+1 ,因此调用 table.insert(t,x) 会在列表 t 的末尾插入 x

table.move (a1, f, e, t [,a2])

Moves elements from the table a1 to the table a2, performing the equivalent to the following multiple assignment: a2[t],··· = a1[f],···,a1[e]. The default for a2 is a1. The destination range can overlap with the source range. The number of elements to be moved must fit in a Lua integer.

​ 将表 a1 中的元素移动到表 a2 中,执行等同于以下多重赋值的操作: a2[t],··· = a1[f],···,a1[e]a2 的默认值为 a1 。目标范围可以与源范围重叠。要移动的元素数量必须适合 Lua 整数。

Returns the destination table a2.

​ 返回目标表 a2

table.pack (···)

Returns a new table with all arguments stored into keys 1, 2, etc. and with a field “n” with the total number of arguments. Note that the resulting table may not be a sequence, if some arguments are nil.

​ 返回一个新表,其中所有参数都存储在键 1、2 等中,并带有字段“ n ”,其中包含参数的总数。请注意,如果某些参数为 nil,则结果表可能不是一个序列。

table.remove (list [, pos])

Removes from list the element at position pos, returning the value of the removed element. When pos is an integer between 1 and #list, it shifts down the elements list[pos+1], list[pos+2], ···, list[#list] and erases element list[#list]; The index pos can also be 0 when #list is 0, or #list + 1.

​ 从 list 中移除位置 pos 处的元素,返回已移除元素的值。当 pos 是 1 到 #list 之间的整数时,它会向下移动元素 list[pos+1], list[pos+2], ···, list[#list] 并擦除元素 list[#list] ;当 #list 为 0 或 #list + 1 时,索引 pos 也可以为 0。

The default value for pos is #list, so that a call table.remove(l) removes the last element of the list l.

pos 的默认值为 #list ,因此调用 table.remove(l) 会移除列表 l 的最后一个元素。

table.sort (list [, comp])

Sorts the list elements in a given order, in-place, from list[1] to list[#list]. If comp is given, then it must be a function that receives two list elements and returns true when the first element must come before the second in the final order, so that, after the sort, i <= j implies not comp(list[j],list[i]). If comp is not given, then the standard Lua operator < is used instead.

​ 按给定顺序对列表元素进行原地排序,从 list[1]list[#list] 。如果给定了 comp ,那么它必须是一个函数,该函数接收两个列表元素,并在第一个元素在最终顺序中必须在第二个元素之前时返回 true,以便在排序后, i <= j 暗示 not comp(list[j],list[i]) 。如果未给出 comp ,则使用标准 Lua 运算符 <

The comp function must define a consistent order; more formally, the function must define a strict weak order. (A weak order is similar to a total order, but it can equate different elements for comparison purposes.)

comp 函数必须定义一个一致的顺序;更正式地说,该函数必须定义一个严格的弱序。(弱序类似于全序,但它可以将不同的元素等同于比较目的。)

The sort algorithm is not stable: Different elements considered equal by the given order may have their relative positions changed by the sort.

​ 排序算法不稳定:由给定顺序视为相等的元素可能会因排序而改变其相对位置。

table.unpack (list [, i [, j]])

Returns the elements from the given list. This function is equivalent to

​ 返回给定列表中的元素。此函数等效于

     return list[i], list[i+1], ···, list[j]
return list[i], list[i+1], ···, list[j]

By default, i is 1 and j is #list.

​ 默认情况下, i 为 1, j#list

6.7 – Mathematical Functions 数学函数

This library provides basic mathematical functions. It provides all its functions and constants inside the table math. Functions with the annotation “integer/float” give integer results for integer arguments and float results for non-integer arguments. The rounding functions math.ceil, math.floor, and math.modf return an integer when the result fits in the range of an integer, or a float otherwise.

​ 此库提供基本数学函数。它在表 math 中提供所有函数和常量。带注释“ integer/float ”的函数为整数参数提供整数结果,为非整数参数提供浮点结果。舍入函数 math.ceilmath.floormath.modf 在结果适合整数范围时返回整数,否则返回浮点数。

math.abs (x)

Returns the maximum value between x and -x. (integer/float)

​ 返回 x-x 之间的最大值。(整数/浮点数)

math.acos (x)

Returns the arc cosine of x (in radians).

​ 返回 x 的反余弦值(以弧度为单位)。

math.asin (x)

Returns the arc sine of x (in radians).

​ 返回 x 的反正弦值(以弧度为单位)。

math.atan (y [, x])

Returns the arc tangent of y/x (in radians), using the signs of both arguments to find the quadrant of the result. It also handles correctly the case of x being zero.

​ 返回 y/x 的反正切值(以弧度为单位),使用两个参数的符号来查找结果的象限。它还正确处理 x 为零的情况。

The default value for x is 1, so that the call math.atan(y) returns the arc tangent of y.

x 的默认值为 1,因此调用 math.atan(y) 返回 y 的反正切值。

math.ceil (x)

Returns the smallest integral value greater than or equal to x.

​ 返回大于或等于 x 的最小整数。

math.cos (x)

Returns the cosine of x (assumed to be in radians).

​ 返回 x 的余弦值(假定以弧度为单位)。

math.deg (x)

Converts the angle x from radians to degrees.

​ 将角度 x 从弧度转换为度数。

math.exp (x)

Returns the value ex (where e is the base of natural logarithms).

​ 返回值 e x (其中 e 是自然对数的底数)。

math.floor (x)

Returns the largest integral value less than or equal to x.

​ 返回小于或等于 x 的最大整数。

math.fmod (x, y)

Returns the remainder of the division of x by y that rounds the quotient towards zero. (integer/float)

​ 返回将 x 除以 y 的余数,该余数将商四舍五入为零。(整数/浮点数)

math.huge

The float value HUGE_VAL, a value greater than any other numeric value.

​ 浮点值 HUGE_VAL ,大于任何其他数值。

math.log (x [, base])

Returns the logarithm of x in the given base. The default for base is e (so that the function returns the natural logarithm of x).

​ 返回以给定底数为底的 x 的对数。 base 的默认值为 e(因此该函数返回 x 的自然对数)。

math.max (x, ···)

Returns the argument with the maximum value, according to the Lua operator <.

​ 根据 Lua 运算符 < 返回具有最大值的参数。

math.maxinteger

An integer with the maximum value for an integer. 具有最大整数值的整数。

math.min (x, ···)

Returns the argument with the minimum value, according to the Lua operator <.

​ 根据 Lua 运算符 < 返回具有最小值的参数。

math.mininteger

An integer with the minimum value for an integer. 具有最小整数值的整数。

math.modf (x)

Returns the integral part of x and the fractional part of x. Its second result is always a float.

​ 返回 x 的整数部分和 x 的小数部分。其第二个结果始终是浮点数。

math.pi

The value of π.

​ π 的值。

math.rad (x)

Converts the angle x from degrees to radians.

​ 将角度 x 从度转换为弧度。

math.random ([m [, n]])

When called without arguments, returns a pseudo-random float with uniform distribution in the range [0,1). When called with two integers m and n, math.random returns a pseudo-random integer with uniform distribution in the range [m, n]. The call math.random(n), for a positive n, is equivalent to math.random(1,n). The call math.random(0) produces an integer with all bits (pseudo)random.

​ 当不带参数调用时,返回一个在 [0,1) 范围内具有均匀分布的伪随机浮点数。当使用两个整数 mn 调用时, math.random 返回一个在 [m, n] 范围内具有均匀分布的伪随机整数。对于正数 n ,调用 math.random(n) 等效于 math.random(1,n) 。调用 math.random(0) 会生成一个所有位都(伪)随机的整数。

This function uses the xoshiro256** algorithm to produce pseudo-random 64-bit integers, which are the results of calls with argument 0. Other results (ranges and floats) are unbiased extracted from these integers.

​ 此函数使用 xoshiro256** 算法生成伪随机 64 位整数,这些整数是使用参数 0 进行调用产生的结果。其他结果(范围和浮点数)是从这些整数中提取的无偏结果。

Lua initializes its pseudo-random generator with the equivalent of a call to math.randomseed with no arguments, so that math.random should generate different sequences of results each time the program runs.

​ Lua 使用相当于不带参数调用 math.randomseed 的方式初始化其伪随机生成器,因此每次程序运行时, math.random 都应生成不同的结果序列。

math.randomseed ([x [, y]])

When called with at least one argument, the integer parameters x and y are joined into a 128-bit seed that is used to reinitialize the pseudo-random generator; equal seeds produce equal sequences of numbers. The default for y is zero.

​ 当至少带一个参数调用时,整数参数 xy 会连接成一个 128 位种子,该种子用于重新初始化伪随机生成器;相等的种子会产生相等数字序列。默认情况下, y 为零。

When called with no arguments, Lua generates a seed with a weak attempt for randomness.

​ 当不带参数调用时,Lua 会生成一个种子,并尝试实现随机性。

This function returns the two seed components that were effectively used, so that setting them again repeats the sequence.

​ 此函数返回实际使用的两个种子组件,以便再次设置它们来重复该序列。

To ensure a required level of randomness to the initial state (or contrarily, to have a deterministic sequence, for instance when debugging a program), you should call math.randomseed with explicit arguments.

​ 为了确保初始状态具有所需的随机性级别(或者相反,为了具有确定性序列,例如在调试程序时),您应该使用显式参数调用 math.randomseed

math.sin (x)

Returns the sine of x (assumed to be in radians).

​ 返回 x 的正弦值(假定以弧度为单位)。

math.sqrt (x)

Returns the square root of x. (You can also use the expression x^0.5 to compute this value.)

​ 返回 x 的平方根。(您也可以使用表达式 x^0.5 来计算此值。)

math.tan (x)

Returns the tangent of x (assumed to be in radians).

​ 返回 x 的正切(假定以弧度为单位)。

math.tointeger (x)

If the value x is convertible to an integer, returns that integer. Otherwise, returns fail.

​ 如果值 x 可转换为整数,则返回该整数。否则,返回失败。

math.type (x)

Returns “integer” if x is an integer, “float” if it is a float, or fail if x is not a number.

​ 如果 x 是整数,则返回“ integer ”;如果它是浮点数,则返回“ float ”;如果 x 不是数字,则返回失败。

math.ult (m, n)

Returns a boolean, true if and only if integer m is below integer n when they are compared as unsigned integers.

​ 返回一个布尔值,当整数 m 在作为无符号整数比较时低于整数 n 时且仅当时返回 true。

6.8 – Input and Output Facilities 输入和输出工具

The I/O library provides two different styles for file manipulation. The first one uses implicit file handles; that is, there are operations to set a default input file and a default output file, and all input/output operations are done over these default files. The second style uses explicit file handles.

​ I/O 库为文件操作提供了两种不同的样式。第一种使用隐式文件句柄;也就是说,有一些操作用于设置默认输入文件和默认输出文件,并且所有输入/输出操作都是通过这些默认文件完成的。第二种样式使用显式文件句柄。

When using implicit file handles, all operations are supplied by table io. When using explicit file handles, the operation io.open returns a file handle and then all operations are supplied as methods of the file handle.

​ 使用隐式文件句柄时,所有操作都由表 io 提供。使用显式文件句柄时,操作 io.open 返回一个文件句柄,然后所有操作都作为文件句柄的方法提供。

The metatable for file handles provides metamethods for __gc and __close that try to close the file when called.

​ 文件句柄的元表为 __gc__close 提供元方法,在调用时尝试关闭文件。

The table io also provides three predefined file handles with their usual meanings from C: io.stdin, io.stdout, and io.stderr. The I/O library never closes these files.

​ 表 io 还提供了三个预定义的文件句柄,它们具有 C 中通常的含义: io.stdinio.stdoutio.stderr 。I/O 库绝不会关闭这些文件。

Unless otherwise stated, all I/O functions return fail on failure, plus an error message as a second result and a system-dependent error code as a third result, and some non-false value on success. On non-POSIX systems, the computation of the error message and error code in case of errors may be not thread safe, because they rely on the global C variable errno.

​ 除非另有说明,否则所有 I/O 函数在失败时返回失败,外加一条错误消息作为第二个结果和一个与系统相关的错误代码作为第三个结果,而在成功时返回某个非假值。在非 POSIX 系统上,在发生错误时计算错误消息和错误代码可能不是线程安全的,因为它们依赖于全局 C 变量 errno

io.close ([file])

Equivalent to file:close(). Without a file, closes the default output file.

​ 等同于 file:close() 。如果没有 file ,则关闭默认输出文件。

io.flush ()

Equivalent to io.output():flush().

​ 等同于 io.output():flush()

io.input ([file])

When called with a file name, it opens the named file (in text mode), and sets its handle as the default input file. When called with a file handle, it simply sets this file handle as the default input file. When called without arguments, it returns the current default input file.

​ 当使用文件名调用时,它会打开指定的文件(以文本模式),并将它的句柄设置为默认输入文件。当使用文件句柄调用时,它会简单地将此文件句柄设置为默认输入文件。当不带参数调用时,它会返回当前的默认输入文件。

In case of errors this function raises the error, instead of returning an error code.

​ 如果发生错误,此函数会引发错误,而不是返回错误代码。

io.lines ([filename, ···])

Opens the given file name in read mode and returns an iterator function that works like file:lines(···) over the opened file. When the iterator function fails to read any value, it automatically closes the file. Besides the iterator function, io.lines returns three other values: two nil values as placeholders, plus the created file handle. Therefore, when used in a generic for loop, the file is closed also if the loop is interrupted by an error or a break.

​ 以读取模式打开给定的文件名,并返回一个类似于 file:lines(···) 的遍历函数,该函数可对打开的文件进行遍历。当遍历函数无法读取任何值时,它会自动关闭文件。除了遍历函数之外, io.lines 还返回三个其他值:两个 nil 值作为占位符,以及创建的文件句柄。因此,当在通用 for 循环中使用时,即使循环因错误或 break 而被终止,文件也会被关闭。

The call io.lines() (with no file name) is equivalent to io.input():lines("l"); that is, it iterates over the lines of the default input file. In this case, the iterator does not close the file when the loop ends.

​ 调用 io.lines() (无文件名)等效于 io.input():lines("l") ;也就是说,它会遍历默认输入文件中的行。在这种情况下,遍历函数在循环结束时不会关闭文件。

In case of errors opening the file, this function raises the error, instead of returning an error code.

​ 如果在打开文件时发生错误,此函数会引发错误,而不是返回错误代码。

io.open (filename [, mode])

This function opens a file, in the mode specified in the string mode. In case of success, it returns a new file handle.

​ 此函数以字符串 mode 中指定的模式打开文件。如果成功,它会返回一个新的文件句柄。

The mode string can be any of the following:

mode 字符串可以是以下任何一个:

  • "r”: read mode (the default); " r “:读取模式(默认值);
  • "w”: write mode; " w “:写入模式;
  • "a”: append mode; " a “:追加模式;
  • "r+”: update mode, all previous data is preserved; " r+ “:更新模式,保留所有以前的数据;
  • "w+”: update mode, all previous data is erased; " w+ “:更新模式,擦除所有以前的数据;
  • "a+”: append update mode, previous data is preserved, writing is only allowed at the end of file. " a+ “: 追加更新模式,保留先前数据,只允许在文件末尾写入。

The mode string can also have a ‘b’ at the end, which is needed in some systems to open the file in binary mode.

mode 字符串末尾还可以有一个 ’ b ‘,在某些系统中需要它来以二进制模式打开文件。

io.output ([file])

Similar to io.input, but operates over the default output file.

​ 与 io.input 类似,但操作的是默认输出文件。

io.popen (prog [, mode])

This function is system dependent and is not available on all platforms.

​ 此函数依赖于系统,并非所有平台都可用。

Starts the program prog in a separated process and returns a file handle that you can use to read data from this program (if mode is "r", the default) or to write data to this program (if mode is "w").

​ 在一个单独的进程中启动程序 prog ,并返回一个文件句柄,您可以使用该句柄从此程序读取数据(如果 mode"r" ,这是默认值)或向此程序写入数据(如果 mode"w" )。

io.read (···)

Equivalent to io.input():read(···).

​ 等同于 io.input():read(···)

io.tmpfile ()

In case of success, returns a handle for a temporary file. This file is opened in update mode and it is automatically removed when the program ends.

​ 如果成功,则返回一个临时文件的句柄。此文件以更新模式打开,并在程序结束时自动删除。

io.type (obj)

Checks whether obj is a valid file handle. Returns the string "file" if obj is an open file handle, "closed file" if obj is a closed file handle, or fail if obj is not a file handle.

​ 检查 obj 是否是有效的文件句柄。如果 obj 是一个打开的文件句柄,则返回字符串 "file" ;如果 obj 是一个关闭的文件句柄,则返回 "closed file" ;如果 obj 不是一个文件句柄,则失败。

io.write (···)

Equivalent to io.output():write(···).

​ 等同于 io.output():write(···)

file:close ()

Closes file. Note that files are automatically closed when their handles are garbage collected, but that takes an unpredictable amount of time to happen.

​ 关闭 file 。请注意,当文件的句柄被垃圾回收时,文件会自动关闭,但这需要花费不可预测的时间。

When closing a file handle created with io.popen, file:close returns the same values returned by os.execute.

​ 在使用 io.popen 创建的文件句柄关闭时, file:close 返回 os.execute 返回的相同值。

file:flush ()

Saves any written data to file.

​ 将任何已写入的数据保存到 file

file:lines (···)

Returns an iterator function that, each time it is called, reads the file according to the given formats. When no format is given, uses “l” as a default. As an example, the construction

​ 返回一个迭代器函数,每次调用时,都会根据给定的格式读取文件。如果没有给出格式,则使用“ l ”作为默认值。例如,构造

     for c in file:lines(1) do body end

will iterate over all characters of the file, starting at the current position. Unlike io.lines, this function does not close the file when the loop ends.

​ 将从当前位置开始迭代文件的所有字符。与 io.lines 不同,此函数在循环结束时不会关闭文件。

file:read (···)

Reads the file file, according to the given formats, which specify what to read. For each format, the function returns a string or a number with the characters read, or fail if it cannot read data with the specified format. (In this latter case, the function does not read subsequent formats.) When called without arguments, it uses a default format that reads the next line (see below).

​ 根据给定的格式读取文件 file ,这些格式指定要读取的内容。对于每种格式,该函数返回一个字符串或一个数字,其中包含已读取的字符,或者如果无法使用指定格式读取数据,则返回失败。(在后一种情况下,该函数不会读取后续格式。)当在没有参数的情况下调用时,它使用读取下一行的默认格式(见下文)。

The available formats are

​ 可用的格式是

  • "n”: reads a numeral and returns it as a float or an integer, following the lexical conventions of Lua. (The numeral may have leading whitespaces and a sign.) This format always reads the longest input sequence that is a valid prefix for a numeral; if that prefix does not form a valid numeral (e.g., an empty string, “0x”, or “3.4e-”) or it is too long (more than 200 characters), it is discarded and the format returns fail. " n “: 读取一个数字并按照 Lua 的词法惯例将其作为浮点数或整数返回。(数字可能带有前导空格和符号。)此格式始终读取最长的输入序列,该序列是数字的有效前缀;如果该前缀未形成有效数字(例如,空字符串、“ 0x ”或“ 3.4e- ”)或太长(超过 200 个字符),则将其丢弃,格式返回失败。
  • "a”: reads the whole file, starting at the current position. On end of file, it returns the empty string; this format never fails. “ a ”:从当前位置开始读取整个文件。在文件末尾,它返回空字符串;此格式绝不会失败。
  • "l”: reads the next line skipping the end of line, returning fail on end of file. This is the default format. “ l ”:读取下一行,跳过行尾,在文件末尾返回失败。这是默认格式。
  • "L”: reads the next line keeping the end-of-line character (if present), returning fail on end of file. “ L ”:读取下一行,保留行尾字符(如果存在),在文件末尾返回失败。
  • *number*: reads a string with up to this number of bytes, returning fail on end of file. If number is zero, it reads nothing and returns an empty string, or fail on end of file. number:读取最多包含此数量字节的字符串,在文件末尾返回失败。如果 number 为零,则不读取任何内容并返回一个空字符串,或在文件末尾返回失败。

The formats “l” and “L” should be used only for text files.

​ 格式“ l ”和“ L ”仅应用于文本文件。

file:seek ([whence [, offset]])

Sets and gets the file position, measured from the beginning of the file, to the position given by offset plus a base specified by the string whence, as follows:

​ 设置和获取文件位置,从文件开头测量,到由 offset 加上字符串 whence 指定的基准位置,如下:

  • "set”: base is position 0 (beginning of the file); " set “: 基准是位置 0(文件开头);
  • "cur”: base is current position; " cur “: 基准是当前位置;
  • "end”: base is end of file; " end “: 基准是文件结尾;

In case of success, seek returns the final file position, measured in bytes from the beginning of the file. If seek fails, it returns fail, plus a string describing the error.

​ 如果成功, seek 返回最终文件位置,以从文件开头开始的字节数为单位进行测量。如果 seek 失败,它将返回失败,外加一个描述错误的字符串。

The default value for whence is "cur", and for offset is 0. Therefore, the call file:seek() returns the current file position, without changing it; the call file:seek("set") sets the position to the beginning of the file (and returns 0); and the call file:seek("end") sets the position to the end of the file, and returns its size.

whence 的默认值为 "cur"offset 的默认值为 0。因此,调用 file:seek() 返回当前文件位置,而不更改它;调用 file:seek("set") 将位置设置为文件开头(并返回 0);调用 file:seek("end") 将位置设置为文件结尾,并返回其大小。

file:setvbuf (mode [, size])

Sets the buffering mode for a file. There are three available modes:

​ 设置文件的缓冲模式。有三种可用模式:

  • "no”: no buffering. " no “: 无缓冲。
  • "full”: full buffering. " full “: 全缓冲。
  • "line”: line buffering. " line “: 行缓冲。

For the last two cases, size is a hint for the size of the buffer, in bytes. The default is an appropriate size.

​ 对于最后两种情况, size 是缓冲区大小的提示(以字节为单位)。默认值是适当的大小。

The specific behavior of each mode is non portable; check the underlying ISO C function setvbuf in your platform for more details.

​ 每种模式的具体行为不可移植;请查看平台中基础的 ISO C 函数 setvbuf 以了解更多详细信息。

file:write (···)

Writes the value of each of its arguments to file. The arguments must be strings or numbers.

​ 将每个参数的值写入 file 。参数必须是字符串或数字。

In case of success, this function returns file.

​ 如果成功,此函数将返回 file

6.9 – Operating System Facilities 操作系统工具

This library is implemented through table os.

​ 此库通过表 os 实现。

os.clock ()

Returns an approximation of the amount in seconds of CPU time used by the program, as returned by the underlying ISO C function clock.

​ 返回程序使用的 CPU 时间(以秒为单位)的近似值,由基础的 ISO C 函数 clock 返回。

os.date ([format [, time]])

Returns a string or a table containing date and time, formatted according to the given string format.

​ 返回一个字符串或一个包含日期和时间的表,根据给定的字符串 format 进行格式化。

If the time argument is present, this is the time to be formatted (see the os.time function for a description of this value). Otherwise, date formats the current time.

​ 如果存在 time 参数,则这是要格式化的时间(请参阅 os.time 函数以获取此值的说明)。否则, date 格式化当前时间。

If format starts with ‘!’, then the date is formatted in Coordinated Universal Time. After this optional character, if format is the string “*t”, then date returns a table with the following fields: year, month (1–12), day (1–31), hour (0–23), min (0–59), sec (0–61, due to leap seconds), wday (weekday, 1–7, Sunday is 1), yday (day of the year, 1–366), and isdst (daylight saving flag, a boolean). This last field may be absent if the information is not available.

​ 如果 format 以“ ! ”开头,则日期格式为协调世界时。在此可选字符之后,如果 format 是字符串“ *t ”,则 date 返回一个包含以下字段的表: yearmonth (1-12)、 day (1-31)、 hour (0-23)、 min (0-59)、 sec (0-61,由于闰秒)、 wday (星期几,1-7,星期日为 1)、 yday (一年中的第几天,1-366)和 isdst (夏令时标志,一个布尔值)。如果信息不可用,则最后一个字段可能不存在。

If format is not “*t”, then date returns the date as a string, formatted according to the same rules as the ISO C function strftime.

​ 如果 format 不是“ *t ”,则 date 会根据与 ISO C 函数 strftime 相同的规则,将日期作为字符串返回,并进行格式化。

If format is absent, it defaults to “%c”, which gives a human-readable date and time representation using the current locale.

​ 如果 format 不存在,则它默认为“ %c ”,它使用当前语言环境提供人类可读的日期和时间表示。

On non-POSIX systems, this function may be not thread safe because of its reliance on C function gmtime and C function localtime.

​ 在非 POSIX 系统上,此函数可能不是线程安全的,因为它依赖于 C 函数 gmtime 和 C 函数 localtime

os.difftime (t2, t1)

Returns the difference, in seconds, from time t1 to time t2 (where the times are values returned by os.time). In POSIX, Windows, and some other systems, this value is exactly t2-t1.

​ 返回从时间 t1 到时间 t2 的差值(以秒为单位)(其中时间是 os.time 返回的值)。在 POSIX、Windows 和其他一些系统中,此值恰好为 t2 - t1

os.execute ([command])

This function is equivalent to the ISO C function system. It passes command to be executed by an operating system shell. Its first result is true if the command terminated successfully, or fail otherwise. After this first result the function returns a string plus a number, as follows:

​ 此函数等同于 ISO C 函数 system 。它将 command 传递给操作系统 shell 执行。如果命令成功终止,则其第一个结果为 true,否则为 fail。在此第一个结果之后,函数返回一个字符串和一个数字,如下所示:

  • "exit”: the command terminated normally; the following number is the exit status of the command. " exit “: 命令正常终止;以下数字是命令的退出状态。
  • "signal”: the command was terminated by a signal; the following number is the signal that terminated the command. " signal “: 命令被信号终止;以下数字是终止命令的信号。

When called without a command, os.execute returns a boolean that is true if a shell is available.

​ 当在没有 command 的情况下调用时, os.execute 返回一个布尔值,如果 shell 可用,则该值为 true。

os.exit ([code [, close]])

Calls the ISO C function exit to terminate the host program. If code is true, the returned status is EXIT_SUCCESS; if code is false, the returned status is EXIT_FAILURE; if code is a number, the returned status is this number. The default value for code is true.

​ 调用 ISO C 函数 exit 来终止主机程序。如果 code 为 true,则返回的状态为 EXIT_SUCCESS ;如果 code 为 false,则返回的状态为 EXIT_FAILURE ;如果 code 是一个数字,则返回的状态是此数字。 code 的默认值为 true。

If the optional second argument close is true, the function closes the Lua state before exiting (see lua_close).

​ 如果可选的第二个参数 close 为 true,则函数在退出之前关闭 Lua 状态(请参阅 lua_close )。

os.getenv (varname)

Returns the value of the process environment variable varname or fail if the variable is not defined.

​ 返回进程环境变量 varname 的值,如果变量未定义,则返回 fail。

os.remove (filename)

Deletes the file (or empty directory, on POSIX systems) with the given name. If this function fails, it returns fail plus a string describing the error and the error code. Otherwise, it returns true.

​ 删除具有给定名称的文件(或在 POSIX 系统上删除空目录)。如果此函数失败,它将返回失败以及描述错误的字符串和错误代码。否则,它将返回 true。

os.rename (oldname, newname)

Renames the file or directory named oldname to newname. If this function fails, it returns fail, plus a string describing the error and the error code. Otherwise, it returns true.

​ 将名为 oldname 的文件或目录重命名为 newname 。如果此函数失败,它将返回失败以及描述错误的字符串和错误代码。否则,它将返回 true。

os.setlocale (locale [, category])

Sets the current locale of the program. locale is a system-dependent string specifying a locale; category is an optional string describing which category to change: "all", "collate", "ctype", "monetary", "numeric", or "time"; the default category is "all". The function returns the name of the new locale, or fail if the request cannot be honored.

​ 设置程序的当前区域设置。 locale 是一个指定区域设置的与系统相关的字符串; category 是一个可选字符串,描述要更改的类别: "all""collate""ctype""monetary""numeric""time" ;默认类别是 "all" 。该函数返回新区域设置的名称,如果无法满足请求,则返回失败。

If locale is the empty string, the current locale is set to an implementation-defined native locale. If locale is the string “C”, the current locale is set to the standard C locale.

​ 如果 locale 是空字符串,则当前区域设置将设置为实现定义的本机区域设置。如果 locale 是字符串“ C ”,则当前区域设置将设置为标准 C 区域设置。

When called with nil as the first argument, this function only returns the name of the current locale for the given category.

​ 当使用 nil 作为第一个参数调用时,此函数仅返回给定类别的当前区域设置的名称。

This function may be not thread safe because of its reliance on C function setlocale.

​ 此函数可能不是线程安全的,因为它依赖于 C 函数 setlocale

os.time ([table])

Returns the current time when called without arguments, or a time representing the local date and time specified by the given table. This table must have fields year, month, and day, and may have fields hour (default is 12), min (default is 0), sec (default is 0), and isdst (default is nil). Other fields are ignored. For a description of these fields, see the os.date function.

​ 在不带参数的情况下调用时返回当前时间,或返回一个表示由给定表指定的时间和日期的时间。此表必须具有字段 yearmonthday ,并且可能具有字段 hour (默认值为 12)、 min (默认值为 0)、 sec (默认值为 0)和 isdst (默认值为 nil)。其他字段将被忽略。有关这些字段的说明,请参阅 os.date 函数。

When the function is called, the values in these fields do not need to be inside their valid ranges. For instance, if sec is -10, it means 10 seconds before the time specified by the other fields; if hour is 1000, it means 1000 hours after the time specified by the other fields.

​ 调用该函数时,这些字段中的值不需要在其有效范围内。例如,如果 sec 为 -10,则表示其他字段指定的时间之前 10 秒;如果 hour 为 1000,则表示其他字段指定的时间之后 1000 小时。

The returned value is a number, whose meaning depends on your system. In POSIX, Windows, and some other systems, this number counts the number of seconds since some given start time (the “epoch”). In other systems, the meaning is not specified, and the number returned by time can be used only as an argument to os.date and os.difftime.

​ 返回值是一个数字,其含义取决于您的系统。在 POSIX、Windows 和其他一些系统中,此数字计算自某个给定开始时间(“纪元”)以来的秒数。在其他系统中,其含义未指定,并且 time 返回的数字只能用作 os.dateos.difftime 的参数。

When called with a table, os.time also normalizes all the fields documented in the os.date function, so that they represent the same time as before the call but with values inside their valid ranges.

​ 当使用一个表调用时, os.time 还将规范化 os.date 函数中记录的所有字段,以便它们表示与调用前相同的时间,但值在有效范围内。

os.tmpname ()

Returns a string with a file name that can be used for a temporary file. The file must be explicitly opened before its use and explicitly removed when no longer needed.

​ 返回一个可用于临时文件的文件名字符串。必须在使用前显式打开文件,并在不再需要时显式删除文件。

In POSIX systems, this function also creates a file with that name, to avoid security risks. (Someone else might create the file with wrong permissions in the time between getting the name and creating the file.) You still have to open the file to use it and to remove it (even if you do not use it).

​ 在 POSIX 系统中,此函数还会创建一个具有该名称的文件,以避免安全风险。(在获取名称和创建文件之间的时间内,其他人可能会创建具有错误权限的文件。)您仍然必须打开文件才能使用它并将其删除(即使您不使用它)。

When possible, you may prefer to use io.tmpfile, which automatically removes the file when the program ends.

​ 如果可能,您可能更喜欢使用 io.tmpfile ,它会在程序结束时自动删除文件。

6.10 – The Debug Library 调试库

This library provides the functionality of the debug interface (§4.7) to Lua programs. You should exert care when using this library. Several of its functions violate basic assumptions about Lua code (e.g., that variables local to a function cannot be accessed from outside; that userdata metatables cannot be changed by Lua code; that Lua programs do not crash) and therefore can compromise otherwise secure code. Moreover, some functions in this library may be slow.

​ 此库为 Lua 程序提供调试接口 (§4.7) 的功能。使用此库时应小心谨慎。它的几个函数违反了 Lua 代码的基本假设(例如,无法从函数外部访问局部变量;用户数据元表无法通过 Lua 代码更改;Lua 程序不会崩溃),因此可能会损害原本安全的代码。此外,此库中的一些函数可能会很慢。

All functions in this library are provided inside the debug table. All functions that operate over a thread have an optional first argument which is the thread to operate over. The default is always the current thread.

​ 此库中的所有函数都提供在 debug 表中。所有针对线程操作的函数都有一个可选的第一个参数,该参数是要操作的线程。默认值始终是当前线程。

debug.debug ()

Enters an interactive mode with the user, running each string that the user enters. Using simple commands and other debug facilities, the user can inspect global and local variables, change their values, evaluate expressions, and so on. A line containing only the word cont finishes this function, so that the caller continues its execution.

​ 以交互模式与用户交互,运行用户输入的每个字符串。通过使用简单命令和其他调试工具,用户可以检查全局变量和局部变量、更改其值、计算表达式等。仅包含单词 cont 的行将结束此函数,以便调用者继续执行。

Note that commands for debug.debug are not lexically nested within any function and so have no direct access to local variables.

​ 请注意, debug.debug 的命令不会在任何函数中进行词法嵌套,因此无法直接访问局部变量。

debug.gethook ([thread])

Returns the current hook settings of the thread, as three values: the current hook function, the current hook mask, and the current hook count, as set by the debug.sethook function.

​ 返回线程的当前挂钩设置,作为三个值:当前挂钩函数、当前挂钩掩码和当前挂钩计数,由 debug.sethook 函数设置。

Returns fail if there is no active hook.

​ 如果没有活动挂钩,则返回失败。

debug.getinfo ([thread,] f [, what])

Returns a table with information about a function. You can give the function directly or you can give a number as the value of f, which means the function running at level f of the call stack of the given thread: level 0 is the current function (getinfo itself); level 1 is the function that called getinfo (except for tail calls, which do not count in the stack); and so on. If f is a number greater than the number of active functions, then getinfo returns fail.

​ 返回有关函数的信息的表。您可以直接给出函数,也可以将数字作为 f 的值,这意味着在给定线程的调用栈的 f 级运行的函数:0 级是当前函数( getinfo 本身);1 级是调用 getinfo 的函数(尾调用除外,尾调用不在栈中计数);依此类推。如果 f 是大于活动函数数量的数字,则 getinfo 返回失败。

The returned table can contain all the fields returned by lua_getinfo, with the string what describing which fields to fill in. The default for what is to get all information available, except the table of valid lines. If present, the option ‘f’ adds a field named func with the function itself. If present, the option ‘L’ adds a field named activelines with the table of valid lines.

​ 返回的表可以包含 lua_getinfo 返回的所有字段,其中字符串 what 描述要填写的字段。 what 的默认值是获取所有可用信息,除了有效行表。如果存在,选项“ f ”会添加一个名为 func 的字段,其中包含函数本身。如果存在,选项“ L ”会添加一个名为 activelines 的字段,其中包含有效行表。

For instance, the expression debug.getinfo(1,"n").name returns a name for the current function, if a reasonable name can be found, and the expression debug.getinfo(print) returns a table with all available information about the print function.

​ 例如,表达式 debug.getinfo(1,"n").name 返回当前函数的名称(如果可以找到合理的名称),表达式 debug.getinfo(print) 返回一个表,其中包含有关 print 函数的所有可用信息。

debug.getlocal ([thread,] f, local)

This function returns the name and the value of the local variable with index local of the function at level f of the stack. This function accesses not only explicit local variables, but also parameters and temporary values.

​ 此函数返回函数在栈的第 f 级中索引为 local 的局部变量的名称和值。此函数不仅访问显式局部变量,还访问参数和临时值。

The first parameter or local variable has index 1, and so on, following the order that they are declared in the code, counting only the variables that are active in the current scope of the function. Compile-time constants may not appear in this listing, if they were optimized away by the compiler. Negative indices refer to vararg arguments; -1 is the first vararg argument. The function returns fail if there is no variable with the given index, and raises an error when called with a level out of range. (You can call debug.getinfo to check whether the level is valid.)

​ 第一个参数或局部变量的索引为 1,依此类推,按照它们在代码中声明的顺序,仅计算函数当前作用域中处于活动状态的变量。如果编译器对编译时常量进行了优化,则这些常量可能不会出现在此列表中。负索引引用可变参数;-1 是第一个可变参数。如果不存在具有给定索引的变量,则函数返回失败,并在调用时引发错误,超出范围的级别。(您可以调用 debug.getinfo 来检查级别是否有效。)

Variable names starting with ‘(’ (open parenthesis) represent variables with no known names (internal variables such as loop control variables, and variables from chunks saved without debug information).

​ 以“ ( ”(左括号)开头的变量名表示没有已知名称的变量(内部变量,如循环控制变量,以及从没有调试信息的块中保存的变量)。

The parameter f may also be a function. In that case, getlocal returns only the name of function parameters.

​ 参数 f 也可能是一个函数。在这种情况下, getlocal 只返回函数参数的名称。

debug.getmetatable (value)

Returns the metatable of the given value or nil if it does not have a metatable.

​ 返回给定 value 的元表,如果没有元表,则返回 nil。

debug.getregistry ()

Returns the registry table (see §4.3).

​ 返回注册表(参见 §4.3)。

debug.getupvalue (f, up)

This function returns the name and the value of the upvalue with index up of the function f. The function returns fail if there is no upvalue with the given index.

​ 此函数返回函数 f 的索引 up 的上值名称和值。如果没有具有给定索引的上值,则函数返回失败。

(For Lua functions, upvalues are the external local variables that the function uses, and that are consequently included in its closure.)

​ (对于 Lua 函数,上值是函数使用的外部局部变量,因此包含在函数的闭包中。)

For C functions, this function uses the empty string "" as a name for all upvalues.

​ 对于 C 函数,此函数使用空字符串 "" 作为所有上值名称。

Variable name ‘?’ (interrogation mark) represents variables with no known names (variables from chunks saved without debug information).

​ 变量名“ ? ”(问号)表示没有已知名称的变量(从没有调试信息的块中保存的变量)。

debug.getuservalue (u, n)

Returns the n-th user value associated to the userdata u plus a boolean, false if the userdata does not have that value.

​ 返回与用户数据 u 关联的第 n 个用户值以及一个布尔值,如果用户数据没有该值,则为 false。

debug.sethook ([thread,] hook, mask [, count])

Sets the given function as the debug hook. The string mask and the number count describe when the hook will be called. The string mask may have any combination of the following characters, with the given meaning:

​ 将给定的函数设置为调试钩子。字符串 mask 和数字 count 描述了钩子何时被调用。字符串掩码可以具有以下字符的任意组合,具有给定的含义:

  • c’: the hook is called every time Lua calls a function; ’ c ‘: 每次 Lua 调用函数时都会调用钩子;
  • r’: the hook is called every time Lua returns from a function; ’ r ‘: 每次 Lua 从函数返回时都会调用钩子;
  • l’: the hook is called every time Lua enters a new line of code. ’ l ‘: 每次 Lua 进入新代码行时都会调用钩子。

Moreover, with a count different from zero, the hook is called also after every count instructions.

​ 此外,当 count 不为零时,每执行 count 条指令后也会调用钩子。

When called without arguments, debug.sethook turns off the hook.

​ 当不带参数调用时, debug.sethook 会关闭钩子。

When the hook is called, its first parameter is a string describing the event that has triggered its call: "call", "tail call", "return", "line", and "count". For line events, the hook also gets the new line number as its second parameter. Inside a hook, you can call getinfo with level 2 to get more information about the running function. (Level 0 is the getinfo function, and level 1 is the hook function.)

​ 当调用钩子时,它的第一个参数是一个字符串,描述触发其调用的事件: "call""tail call""return""line""count" 。对于行事件,钩子还将新行号作为其第二个参数。在钩子内部,您可以使用级别 2 调用 getinfo 以获取有关正在运行的函数的更多信息。(级别 0 是 getinfo 函数,级别 1 是钩子函数。)

debug.setlocal ([thread,] level, local, value)

This function assigns the value value to the local variable with index local of the function at level level of the stack. The function returns fail if there is no local variable with the given index, and raises an error when called with a level out of range. (You can call getinfo to check whether the level is valid.) Otherwise, it returns the name of the local variable.

​ 此函数将值 value 分配给栈第 level 层函数的索引为 local 的局部变量。如果不存在具有给定索引的局部变量,则该函数返回失败,并在调用时引发错误,超出范围 level 。(您可以调用 getinfo 来检查该层是否有效。)否则,它将返回局部变量的名称。

See debug.getlocal for more information about variable indices and names.

​ 有关变量索引和名称的更多信息,请参见 debug.getlocal

debug.setmetatable (value, table)

Sets the metatable for the given value to the given table (which can be nil). Returns value.

​ 将给定 value 的元表设置为给定的 table (可以为 nil)。返回 value

debug.setupvalue (f, up, value)

This function assigns the value value to the upvalue with index up of the function f. The function returns fail if there is no upvalue with the given index. Otherwise, it returns the name of the upvalue.

​ 此函数将值 value 分配给函数 f 的索引为 up 的上值。如果不存在具有给定索引的上值,则该函数返回失败。否则,它将返回上值的名字。

See debug.getupvalue for more information about upvalues.

​ 有关上值的更多信息,请参见 debug.getupvalue

debug.setuservalue (udata, value, n)

Sets the given value as the n-th user value associated to the given udata. udata must be a full userdata.

​ 将给定的 value 设置为与给定的 udata 关联的第 n 个用户值。 udata 必须是完整用户数据。

Returns udata, or fail if the userdata does not have that value.

​ 返回 udata ,如果用户数据没有该值,则返回失败。

debug.traceback ([thread,] [message [, level]])

If message is present but is neither a string nor nil, this function returns message without further processing. Otherwise, it returns a string with a traceback of the call stack. The optional message string is appended at the beginning of the traceback. An optional level number tells at which level to start the traceback (default is 1, the function calling traceback).

​ 如果 message 存在但既不是字符串也不是nil,此函数将返回 message ,而不会进一步处理。否则,它将返回一个字符串,其中包含调用栈的回溯。可选的 message 字符串附加在回溯的开头。可选的 level 数字告诉从哪个级别开始回溯(默认值为1,即调用 traceback 的函数)。

debug.upvalueid (f, n)

Returns a unique identifier (as a light userdata) for the upvalue numbered n from the given function.

​ 为给定函数中编号为 n 的上值返回一个唯一标识符(作为轻量级用户数据)。

These unique identifiers allow a program to check whether different closures share upvalues. Lua closures that share an upvalue (that is, that access a same external local variable) will return identical ids for those upvalue indices.

​ 这些唯一标识符允许程序检查不同的闭包是否共享上值。共享上值的Lua闭包(即访问相同的外部局部变量)将为这些上值索引返回相同的id。

debug.upvaluejoin (f1, n1, f2, n2)

Make the n1-th upvalue of the Lua closure f1 refer to the n2-th upvalue of the Lua closure f2.

​ 使Lua闭包 f1 的第 n1 个上值引用Lua闭包 f2 的第 n2 个上值。

最后修改 January 31, 2024: 更新 (e0896df)