4 – 应用程序接口
62 分钟阅读
4 – The Application Program Interface – 应用程序接口
This section describes the C API for Lua, that is, the set of C functions available to the host program to communicate with Lua. All API functions and related types and constants are declared in the header file lua.h
.
本节介绍 Lua 的 C API,即主机程序可用来与 Lua 通信的一组 C 函数。所有 API 函数以及相关的类型和常量都在头文件 lua.h
中声明。
Even when we use the term “function”, any facility in the API may be provided as a macro instead. Except where stated otherwise, all such macros use each of their arguments exactly once (except for the first argument, which is always a Lua state), and so do not generate any hidden side-effects.
即使我们使用术语“函数”,API 中的任何工具都可以作为宏来提供。除非另有说明,所有此类宏都只使用其每个参数一次(第一个参数除外,它始终是 Lua 状态),因此不会产生任何隐藏的副作用。
As in most C libraries, the Lua API functions do not check their arguments for validity or consistency. However, you can change this behavior by compiling Lua with the macro LUA_USE_APICHECK
defined.
与大多数 C 库一样,Lua API 函数不会检查其参数的有效性或一致性。但是,您可以通过使用已定义的宏 LUA_USE_APICHECK
编译 Lua 来更改此行为。
The Lua library is fully reentrant: it has no global variables. It keeps all information it needs in a dynamic structure, called the Lua state.
Lua 库是完全可重入的:它没有全局变量。它将所需的所有信息保存在一个称为 Lua 状态的动态结构中。
Each Lua state has one or more threads, which correspond to independent, cooperative lines of execution. The type lua_State
(despite its name) refers to a thread. (Indirectly, through the thread, it also refers to the Lua state associated to the thread.)
每个 Lua 状态都有一个或多个线程,它们对应于独立的协作执行行。类型 lua_State
(尽管其名称如此)是指线程。(间接地,通过线程,它还指与线程关联的 Lua 状态。)
A pointer to a thread must be passed as the first argument to every function in the library, except to lua_newstate
, which creates a Lua state from scratch and returns a pointer to the main thread in the new state.
必须将指向线程的指针作为库中每个函数的第一个参数传递,除了 lua_newstate
,它从头开始创建一个 Lua 状态并返回指向新状态中主线程的指针。
4.1 – The Stack 栈
Lua uses a virtual stack to pass values to and from C. Each element in this stack represents a Lua value (nil, number, string, etc.). Functions in the API can access this stack through the Lua state parameter that they receive.
Lua 使用虚拟栈向 C 传递值并从 C 接收值。此栈中的每个元素都表示一个 Lua 值(nil、数字、字符串等)。API 中的函数可以通过它们接收的 Lua 状态参数访问此栈。
Whenever Lua calls C, the called function gets a new stack, which is independent of previous stacks and of stacks of C functions that are still active. This stack initially contains any arguments to the C function and it is where the C function can store temporary Lua values and must push its results to be returned to the caller (see lua_CFunction
).
每当 Lua 调用 C 时,被调用的函数都会获得一个新栈,该栈独立于以前的栈和仍处于活动状态的 C 函数的栈。此栈最初包含对 C 函数的任何参数,C 函数可以在其中存储临时 Lua 值,并且必须将结果推送到要返回给调用者的位置(请参阅 lua_CFunction
)。
For convenience, most query operations in the API do not follow a strict stack discipline. Instead, they can refer to any element in the stack by using an index: A positive index represents an absolute stack position, starting at 1 as the bottom of the stack; a negative index represents an offset relative to the top of the stack. More specifically, if the stack has n elements, then index 1 represents the first element (that is, the element that was pushed onto the stack first) and index n represents the last element; index -1 also represents the last element (that is, the element at the top) and index -n represents the first element.
为了方便起见,API 中的大多数查询操作不会遵循严格的栈规则。相反,它们可以通过使用索引来引用栈中的任何元素:正索引表示绝对栈位置,从 1 开始作为栈的底部;负索引表示相对于栈顶部的偏移量。更具体地说,如果栈有 n 个元素,则索引 1 表示第一个元素(即首先推入栈的元素),索引 n 表示最后一个元素;索引 -1 也表示最后一个元素(即顶部的元素),索引 -n 表示第一个元素。
4.1.1 – Stack Size 栈大小
When you interact with the Lua API, you are responsible for ensuring consistency. In particular, you are responsible for controlling stack overflow. When you call any API function, you must ensure the stack has enough room to accommodate the results.
当您与 Lua API 交互时,您有责任确保一致性。特别是,您有责任控制栈溢出。当您调用任何 API 函数时,您必须确保栈有足够的空间来容纳结果。
There is one exception to the above rule: When you call a Lua function without a fixed number of results (see lua_call
), Lua ensures that the stack has enough space for all results. However, it does not ensure any extra space. So, before pushing anything on the stack after such a call you should use lua_checkstack
.
对于上述规则有一个例外:当您调用没有固定结果数量的 Lua 函数时(请参阅 lua_call
),Lua 会确保栈有足够的空间来容纳所有结果。但是,它不会确保任何额外的空间。因此,在对此类调用之后将任何内容推送到栈之前,您应该使用 lua_checkstack
。
Whenever Lua calls C, it ensures that the stack has space for at least LUA_MINSTACK
extra elements; that is, you can safely push up to LUA_MINSTACK
values into it. LUA_MINSTACK
is defined as 20, so that usually you do not have to worry about stack space unless your code has loops pushing elements onto the stack. Whenever necessary, you can use the function lua_checkstack
to ensure that the stack has enough space for pushing new elements.
每当 Lua 调用 C 时,它都会确保栈至少有 LUA_MINSTACK
个额外的元素空间;也就是说,您最多可以安全地将 LUA_MINSTACK
个值推入其中。 LUA_MINSTACK
被定义为 20,因此通常您不必担心栈空间,除非您的代码有将元素推送到栈的循环。在必要时,您可以使用函数 lua_checkstack
来确保栈有足够的空间来推送新元素。
4.1.2 – Valid and Acceptable Indices 有效和可接受的索引
Any function in the API that receives stack indices works only with valid indices or acceptable indices.
API 中接收栈索引的任何函数仅适用于有效索引或可接受索引。
A valid index is an index that refers to a position that stores a modifiable Lua value. It comprises stack indices between 1 and the stack top (1 ≤ abs(index) ≤ top
) plus pseudo-indices, which represent some positions that are accessible to C code but that are not in the stack. Pseudo-indices are used to access the registry (see §4.3) and the upvalues of a C function (see §4.2).
有效索引是指引用存储可修改 Lua 值的位置的索引。它包括 1 到栈顶 ( 1 ≤ abs(index) ≤ top
) 之间的栈索引以及伪索引,伪索引表示可供 C 代码访问但不在栈中的某些位置。伪索引用于访问注册表(参见 §4.3)和 C 函数的上值(参见 §4.2)。
Functions that do not need a specific mutable position, but only a value (e.g., query functions), can be called with acceptable indices. An acceptable index can be any valid index, but it also can be any positive index after the stack top within the space allocated for the stack, that is, indices up to the stack size. (Note that 0 is never an acceptable index.) Indices to upvalues (see §4.2) greater than the real number of upvalues in the current C function are also acceptable (but invalid). Except when noted otherwise, functions in the API work with acceptable indices.
不需要特定可变位置但仅需要一个值(例如,查询函数)的函数可以使用可接受的索引调用。可接受的索引可以是任何有效索引,但它也可以是栈顶之后栈空间中分配的任何正索引,即索引最多可达栈大小。(请注意,0 永远不是可接受的索引。)大于当前 C 函数中实际数量的上值索引(参见 §4.2)也是可接受的(但无效)。除非另有说明,否则 API 中的函数使用可接受的索引。
Acceptable indices serve to avoid extra tests against the stack top when querying the stack. For instance, a C function can query its third argument without the need to check whether there is a third argument, that is, without the need to check whether 3 is a valid index.
可接受的索引有助于在查询栈时避免对栈顶部的额外测试。例如,C 函数可以查询其第三个参数,而无需检查是否存在第三个参数,即无需检查 3 是否为有效索引。
For functions that can be called with acceptable indices, any non-valid index is treated as if it contains a value of a virtual type LUA_TNONE
, which behaves like a nil value.
对于可以调用具有可接受索引的函数,任何无效索引都将被视为包含虚拟类型 LUA_TNONE
的值,该值的行为类似于 nil 值。
4.1.3 – Pointers to strings 指向字符串的指针
Several functions in the API return pointers (const char*
) to Lua strings in the stack. (See lua_pushfstring
, lua_pushlstring
, lua_pushstring
, and lua_tolstring
. See also luaL_checklstring
, luaL_checkstring
, and luaL_tolstring
in the auxiliary library.)
API 中的几个函数返回栈中 Lua 字符串的指针 ( const char*
)。(请参阅 lua_pushfstring
、 lua_pushlstring
、 lua_pushstring
和 lua_tolstring
。另请参阅辅助库中的 luaL_checklstring
、 luaL_checkstring
和 luaL_tolstring
。)
In general, Lua’s garbage collection can free or move internal memory and then invalidate pointers to internal strings. To allow a safe use of these pointers, the API guarantees that any pointer to a string in a stack index is valid while the string value at that index is not removed from the stack. (It can be moved to another index, though.) When the index is a pseudo-index (referring to an upvalue), the pointer is valid while the corresponding call is active and the corresponding upvalue is not modified.
通常,Lua 的垃圾回收可以释放或移动内部内存,然后使指向内部字符串的指针无效。为了允许安全使用这些指针,API 保证栈索引中的任何字符串指针在该索引处的字符串值未从栈中移除时有效。(不过,它可以移动到另一个索引。)当索引是伪索引(指向上值)时,指针在相应调用处于活动状态且相应上值未修改时有效。
Some functions in the debug interface also return pointers to strings, namely lua_getlocal
, lua_getupvalue
, lua_setlocal
, and lua_setupvalue
. For these functions, the pointer is guaranteed to be valid while the caller function is active and the given closure (if one was given) is in the stack.
调试接口中的一些函数也返回指向字符串的指针,即 lua_getlocal
、 lua_getupvalue
、 lua_setlocal
和 lua_setupvalue
。对于这些函数,保证在调用函数处于活动状态且给定的闭包(如果给出了闭包)在栈中时指针有效。
Except for these guarantees, the garbage collector is free to invalidate any pointer to internal strings.
除这些保证外,垃圾回收器可以使指向内部字符串的任何指针无效。
4.2 – C Closures C 闭包
When a C function is created, it is possible to associate some values with it, thus creating a C closure (see lua_pushcclosure
); these values are called upvalues and are accessible to the function whenever it is called.
创建 C 函数时,可以将一些值与它关联,从而创建一个 C 闭包(参见 lua_pushcclosure
);这些值称为上值,并且在每次调用函数时都可以访问这些值。
Whenever a C function is called, its upvalues are located at specific pseudo-indices. These pseudo-indices are produced by the macro lua_upvalueindex
. The first upvalue associated with a function is at index lua_upvalueindex(1)
, and so on. Any access to lua_upvalueindex(*n*)
, where n is greater than the number of upvalues of the current function (but not greater than 256, which is one plus the maximum number of upvalues in a closure), produces an acceptable but invalid index.
每当调用 C 函数时,其上值都位于特定的伪索引处。这些伪索引由宏 lua_upvalueindex
生成。与函数关联的第一个上值位于索引 lua_upvalueindex(1)
处,依此类推。对 lua_upvalueindex(*n*)
的任何访问,其中 n 大于当前函数的上值数(但不大于 256,即闭包中上值数的最大值加一),都会产生一个可接受但无效的索引。
A C closure can also change the values of its corresponding upvalues.
C 闭包还可以更改其相应上值的值。
4.3 – Registry 注册表
Lua provides a registry, a predefined table that can be used by any C code to store whatever Lua values it needs to store. The registry table is always accessible at pseudo-index LUA_REGISTRYINDEX
. Any C library can store data into this table, but it must take care to choose keys that are different from those used by other libraries, to avoid collisions. Typically, you should use as key a string containing your library name, or a light userdata with the address of a C object in your code, or any Lua object created by your code. As with variable names, string keys starting with an underscore followed by uppercase letters are reserved for Lua.
Lua 提供了一个注册表,这是一个预定义的表,任何 C 代码都可以使用它来存储它需要存储的任何 Lua 值。注册表始终可以在伪索引 LUA_REGISTRYINDEX
处访问。任何 C 库都可以将数据存储到此表中,但它必须注意选择与其他库使用的键不同的键,以避免冲突。通常,您应该使用包含库名称的字符串、带有代码中 C 对象地址的轻量级用户数据或由代码创建的任何 Lua 对象作为键。与变量名一样,以下划线开头并后跟大写字母的字符串键专用于 Lua。
The integer keys in the registry are used by the reference mechanism (see luaL_ref
) and by some predefined values. Therefore, integer keys in the registry must not be used for other purposes.
注册表中的整数键由引用机制(参见 luaL_ref
)和一些预定义值使用。因此,注册表中的整数键不得用于其他目的。
When you create a new Lua state, its registry comes with some predefined values. These predefined values are indexed with integer keys defined as constants in lua.h
. The following constants are defined:
当您创建一个新的 Lua 状态时,其注册表会带有一些预定义值。这些预定义值使用 lua.h
中定义为常量的整数键进行索引。定义了以下常量:
LUA_RIDX_MAINTHREAD
: At this index the registry has the main thread of the state. (The main thread is the one created together with the state.)LUA_RIDX_MAINTHREAD
:在此索引处,注册表具有状态的主线程。(主线程是与状态一起创建的线程。)LUA_RIDX_GLOBALS
: At this index the registry has the global environment.LUA_RIDX_GLOBALS
:在此索引处,注册表具有全局环境。
4.4 – Error Handling in C C 中的错误处理
Internally, Lua uses the C longjmp
facility to handle errors. (Lua will use exceptions if you compile it as C++; search for LUAI_THROW
in the source code for details.) When Lua faces any error, such as a memory allocation error or a type error, it raises an error; that is, it does a long jump. A protected environment uses setjmp
to set a recovery point; any error jumps to the most recent active recovery point.
在内部,Lua 使用 C longjmp
工具来处理错误。(如果您将其编译为 C++,Lua 将使用异常;在源代码中搜索 LUAI_THROW
以获取详细信息。)当 Lua 遇到任何错误(例如内存分配错误或类型错误)时,它会引发错误;也就是说,它会进行远跳转。受保护的环境使用 setjmp
来设置恢复点;任何错误都会跳转到最近的活动恢复点。
Inside a C function you can raise an error explicitly by calling lua_error
.
在 C 函数中,您可以通过调用 lua_error
来显式引发错误。
Most functions in the API can raise an error, for instance due to a memory allocation error. The documentation for each function indicates whether it can raise errors.
API 中的大多数函数都会引发错误,例如由于内存分配错误。每个函数的文档都会指明它是否会引发错误。
If an error happens outside any protected environment, Lua calls a panic function (see lua_atpanic
) and then calls abort
, thus exiting the host application. Your panic function can avoid this exit by never returning (e.g., doing a long jump to your own recovery point outside Lua).
如果在任何受保护环境之外发生错误,Lua 会调用 panic 函数(请参阅 lua_atpanic
),然后调用 abort
,从而退出宿主应用程序。您的 panic 函数可以通过从不返回(例如,执行长跳转到 Lua 外部的您自己的恢复点)来避免此退出。
The panic function, as its name implies, is a mechanism of last resort. Programs should avoid it. As a general rule, when a C function is called by Lua with a Lua state, it can do whatever it wants on that Lua state, as it should be already protected. However, when C code operates on other Lua states (e.g., a Lua-state argument to the function, a Lua state stored in the registry, or the result of lua_newthread
), it should use them only in API calls that cannot raise errors.
panic 函数顾名思义,是一种最后的手段机制。程序应避免使用它。作为一般规则,当 Lua 使用 Lua 状态调用 C 函数时,它可以在该 Lua 状态上执行任何操作,因为它应该已经受到保护。但是,当 C 代码在其他 Lua 状态上运行时(例如,函数的 Lua 状态参数、存储在注册表中的 Lua 状态或 lua_newthread
的结果),它应该仅在不会引发错误的 API 调用中使用它们。
The panic function runs as if it were a message handler (see §2.3); in particular, the error object is on the top of the stack. However, there is no guarantee about stack space. To push anything on the stack, the panic function must first check the available space (see §4.1.1).
panic 函数以消息处理程序的方式运行(参见 §2.3);特别是,错误对象位于栈顶部。但是,栈空间没有任何保证。要将任何内容推送到栈,panic 函数必须首先检查可用空间(参见 §4.1.1)。
4.4.1 – Status Codes 状态码
Several functions that report errors in the API use the following status codes to indicate different kinds of errors or other conditions:
API 中报告错误的几个函数使用以下状态码来指示不同种类的错误或其他情况:
LUA_OK
(0): no errors.LUA_OK
(0):没有错误。LUA_ERRRUN
: a runtime error.LUA_ERRRUN
:运行时错误。LUA_ERRMEM
: memory allocation error. For such errors, Lua does not call the message handler.LUA_ERRMEM
:内存分配错误。对于此类错误,Lua 不会调用消息处理程序。LUA_ERRERR
: error while running the message handler.LUA_ERRERR
:运行消息处理程序时出错。LUA_ERRSYNTAX
: syntax error during precompilation.LUA_ERRSYNTAX
:预编译期间的语法错误。LUA_YIELD
: the thread (coroutine) yields.LUA_YIELD
:线程(协程)让步。LUA_ERRFILE
: a file-related error; e.g., it cannot open or read the file.LUA_ERRFILE
:与文件相关错误;例如,它无法打开或读取文件。
These constants are defined in the header file lua.h
.
这些常量在头文件 lua.h
中定义。
4.5 – Handling Yields in C 在 C 中处理 Yield
Internally, Lua uses the C longjmp
facility to yield a coroutine. Therefore, if a C function foo
calls an API function and this API function yields (directly or indirectly by calling another function that yields), Lua cannot return to foo
any more, because the longjmp
removes its frame from the C stack.
在内部,Lua 使用 C longjmp
工具来生成协程。因此,如果 C 函数 foo
调用 API 函数,并且此 API 函数生成(直接或间接地通过调用生成的其他函数),Lua 将无法再返回到 foo
,因为 longjmp
从 C 栈中删除了其帧。
To avoid this kind of problem, Lua raises an error whenever it tries to yield across an API call, except for three functions: lua_yieldk
, lua_callk
, and lua_pcallk
. All those functions receive a continuation function (as a parameter named k
) to continue execution after a yield.
为了避免此类问题,Lua 在尝试跨 API 调用生成时引发错误,但有三个函数除外: lua_yieldk
、 lua_callk
和 lua_pcallk
。所有这些函数都接收一个延续函数(作为名为 k
的参数)以在生成后继续执行。
We need to set some terminology to explain continuations. We have a C function called from Lua which we will call the original function. This original function then calls one of those three functions in the C API, which we will call the callee function, that then yields the current thread. This can happen when the callee function is lua_yieldk
, or when the callee function is either lua_callk
or lua_pcallk
and the function called by them yields.
我们需要设置一些术语来解释延续。我们有一个从 Lua 调用的 C 函数,我们称之为原始函数。然后,此原始函数调用 C API 中的这三个函数之一,我们称之为被调用函数,然后生成当前线程。当被调用函数是 lua_yieldk
时,或者当被调用函数是 lua_callk
或 lua_pcallk
并且它们调用的函数生成时,可能会发生这种情况。
Suppose the running thread yields while executing the callee function. After the thread resumes, it eventually will finish running the callee function. However, the callee function cannot return to the original function, because its frame in the C stack was destroyed by the yield. Instead, Lua calls a continuation function, which was given as an argument to the callee function. As the name implies, the continuation function should continue the task of the original function.
假设运行线程在执行被调用函数时产生。在该线程恢复后,它最终将完成运行被调用函数。但是,被调用函数无法返回到原始函数,因为其在 C 栈中的帧已被产生所销毁。相反,Lua 调用一个延续函数,该函数作为参数提供给被调用函数。顾名思义,延续函数应继续执行原始函数的任务。
As an illustration, consider the following function:
作为说明,请考虑以下函数:
int original_function (lua_State *L) {
... /* code 1 */
status = lua_pcall(L, n, m, h); /* calls Lua */
... /* code 2 */
}
Now we want to allow the Lua code being run by lua_pcall
to yield. First, we can rewrite our function like here:
现在我们希望允许 Lua 代码通过 lua_pcall
运行以产生。首先,我们可以像这里一样重写我们的函数:
int k (lua_State *L, int status, lua_KContext ctx) {
... /* code 2 */
}
int original_function (lua_State *L) {
... /* code 1 */
return k(L, lua_pcall(L, n, m, h), ctx);
}
In the above code, the new function k
is a continuation function (with type lua_KFunction
), which should do all the work that the original function was doing after calling lua_pcall
. Now, we must inform Lua that it must call k
if the Lua code being executed by lua_pcall
gets interrupted in some way (errors or yielding), so we rewrite the code as here, replacing lua_pcall
by lua_pcallk
:
在上面的代码中,新函数 k
是一个延续函数(类型为 lua_KFunction
),它应该完成原始函数在调用 lua_pcall
之后所做的所有工作。现在,我们必须通知 Lua,如果通过 lua_pcall
执行的 Lua 代码以某种方式(错误或产生)被中断,它必须调用 k
,因此我们将代码重写为这里,用 lua_pcallk
替换 lua_pcall
:
int original_function (lua_State *L) {
... /* code 1 */
return k(L, lua_pcallk(L, n, m, h, ctx2, k), ctx1);
}
Note the external, explicit call to the continuation: Lua will call the continuation only if needed, that is, in case of errors or resuming after a yield. If the called function returns normally without ever yielding, lua_pcallk
(and lua_callk
) will also return normally. (Of course, instead of calling the continuation in that case, you can do the equivalent work directly inside the original function.)
注意对延续的外部显式调用:Lua 仅在需要时才调用延续,即在发生错误或在让步后恢复时。如果被调用的函数正常返回而从不让步, lua_pcallk
(和 lua_callk
)也将正常返回。(当然,在这种情况下,您可以直接在原始函数中执行等效的工作,而不是调用延续。)
Besides the Lua state, the continuation function has two other parameters: the final status of the call and the context value (ctx
) that was passed originally to lua_pcallk
. Lua does not use this context value; it only passes this value from the original function to the continuation function. For lua_pcallk
, the status is the same value that would be returned by lua_pcallk
, except that it is LUA_YIELD
when being executed after a yield (instead of LUA_OK
). For lua_yieldk
and lua_callk
, the status is always LUA_YIELD
when Lua calls the continuation. (For these two functions, Lua will not call the continuation in case of errors, because they do not handle errors.) Similarly, when using lua_callk
, you should call the continuation function with LUA_OK
as the status. (For lua_yieldk
, there is not much point in calling directly the continuation function, because lua_yieldk
usually does not return.)
除了 Lua 状态,延续函数还有两个其他参数:调用的最终状态和最初传递给 lua_pcallk
的上下文值 ( ctx
)。Lua 不使用此上下文值;它仅将此值从原始函数传递到延续函数。对于 lua_pcallk
,状态是 lua_pcallk
将返回的相同值,除了在 yield 之后执行时为 LUA_YIELD
(而不是 LUA_OK
)。对于 lua_yieldk
和 lua_callk
,当 Lua 调用延续时,状态始终为 LUA_YIELD
。(对于这两个函数,Lua 在发生错误时不会调用延续,因为它们不处理错误。)同样,在使用 lua_callk
时,您应该使用 LUA_OK
作为状态来调用延续函数。(对于 lua_yieldk
,直接调用延续函数并没有多大意义,因为 lua_yieldk
通常不会返回。)
Lua treats the continuation function as if it were the original function. The continuation function receives the same Lua stack from the original function, in the same state it would be if the callee function had returned. (For instance, after a lua_callk
the function and its arguments are removed from the stack and replaced by the results from the call.) It also has the same upvalues. Whatever it returns is handled by Lua as if it were the return of the original function.
Lua 将延续函数视为原始函数。延续函数从原始函数接收相同的 Lua 栈,状态与被调用函数返回时相同。(例如,在 lua_callk
之后,函数及其参数从栈中删除,并由调用的结果替换。)它也具有相同的 upvalue。它返回的任何内容都由 Lua 处理,就好像它是原始函数的返回值一样。
4.6 – Functions and Types 函数和类型
Here we list all functions and types from the C API in alphabetical order. Each function has an indicator like this:
此处按字母顺序列出 C API 中的所有函数和类型。每个函数都有一个指示符,如下所示:[-o, +p, x]
The first field, o
, is how many elements the function pops from the stack. The second field, p
, is how many elements the function pushes onto the stack. (Any function always pushes its results after popping its arguments.) A field in the form x|y
means the function can push (or pop) x
or y
elements, depending on the situation; an interrogation mark ‘?
’ means that we cannot know how many elements the function pops/pushes by looking only at its arguments. (For instance, they may depend on what is in the stack.) The third field, x
, tells whether the function may raise errors: ‘-
’ means the function never raises any error; ‘m
’ means the function may raise only out-of-memory errors; ‘v
’ means the function may raise the errors explained in the text; ‘e
’ means the function can run arbitrary Lua code, either directly or through metamethods, and therefore may raise any errors.
第一个字段 o
是函数从栈中弹出的元素数量。第二个字段 p
是函数推入栈的元素数量。(任何函数在弹出其参数后总是会推入其结果。)形式为 x|y
的字段表示函数可以推入(或弹出) x
或 y
个元素,具体取决于情况;问号“ ?
”表示我们无法仅通过查看函数的参数来知道函数弹出/推入多少个元素。(例如,它们可能取决于栈中的内容。)第三个字段 x
告诉函数是否可能引发错误:“ -
”表示函数从不引发任何错误;“ m
”表示函数可能只引发内存不足错误;“ v
”表示函数可能引发文本中解释的错误;“ e
”表示函数可以直接或通过元方法运行任意 Lua 代码,因此可能引发任何错误。
lua_absindex
[-0, +0, –]
int lua_absindex (lua_State *L, int idx);
Converts the acceptable index idx
into an equivalent absolute index (that is, one that does not depend on the stack size).
将可接受的索引 idx
转换为等效的绝对索引(即不依赖于栈大小的索引)。
lua_Alloc
typedef void * (*lua_Alloc) (void *ud,
void *ptr,
size_t osize,
size_t nsize);
The type of the memory-allocation function used by Lua states. The allocator function must provide a functionality similar to realloc
, but not exactly the same. Its arguments are ud
, an opaque pointer passed to lua_newstate
; ptr
, a pointer to the block being allocated/reallocated/freed; osize
, the original size of the block or some code about what is being allocated; and nsize
, the new size of the block.
Lua 状态使用的内存分配函数的类型。分配器函数必须提供类似于 realloc
的功能,但并不完全相同。它的参数是 ud
,传递给 lua_newstate
的一个不透明指针; ptr
,指向正在分配/重新分配/释放的块的指针; osize
,块的原始大小或有关正在分配的内容的一些代码; nsize
,块的新大小。
When ptr
is not NULL
, osize
is the size of the block pointed by ptr
, that is, the size given when it was allocated or reallocated.
当 ptr
不等于 NULL
时, osize
是由 ptr
指向的块的大小,即在分配或重新分配时给定的大小。
When ptr
is NULL
, osize
encodes the kind of object that Lua is allocating. osize
is any of LUA_TSTRING
, LUA_TTABLE
, LUA_TFUNCTION
, LUA_TUSERDATA
, or LUA_TTHREAD
when (and only when) Lua is creating a new object of that type. When osize
is some other value, Lua is allocating memory for something else.
当 ptr
等于 NULL
时, osize
编码 Lua 正在分配的对象的类型。当(且仅当)Lua 创建该类型的新对象时, osize
是 LUA_TSTRING
、 LUA_TTABLE
、 LUA_TFUNCTION
、 LUA_TUSERDATA
或 LUA_TTHREAD
中的任意一个。当 osize
是其他值时,Lua 正在为其他东西分配内存。
Lua assumes the following behavior from the allocator function:
Lua 假设分配器函数具有以下行为:
When nsize
is zero, the allocator must behave like free
and then return NULL
.
当 nsize
为零时,分配器必须表现得像 free
,然后返回 NULL
。
When nsize
is not zero, the allocator must behave like realloc
. In particular, the allocator returns NULL
if and only if it cannot fulfill the request.
当 nsize
不为零时,分配器必须表现得像 realloc
。特别是,当且仅当分配器无法满足请求时,分配器才返回 NULL
。
Here is a simple implementation for the allocator function. It is used in the auxiliary library by luaL_newstate
.
以下是分配器函数的一个简单实现。它由 luaL_newstate
在辅助库中使用。
static void *l_alloc (void *ud, void *ptr, size_t osize,
size_t nsize) {
(void)ud; (void)osize; /* not used */
if (nsize == 0) {
free(ptr);
return NULL;
}
else
return realloc(ptr, nsize);
}
Note that ISO C ensures that free(NULL)
has no effect and that realloc(NULL,size)
is equivalent to malloc(size)
.
请注意,ISO C 确保 free(NULL)
无效,并且 realloc(NULL,size)
等于 malloc(size)
。
lua_arith
[-(2|1), +1, e]
void lua_arith (lua_State *L, int op);
Performs an arithmetic or bitwise operation over the two values (or one, in the case of negations) at the top of the stack, with the value on the top being the second operand, pops these values, and pushes the result of the operation. The function follows the semantics of the corresponding Lua operator (that is, it may call metamethods).
对栈顶的两个值(或一个值,在取反的情况下)执行算术或按位操作,其中栈顶的值为第二个操作数,弹出这些值,并将操作结果压入栈中。该函数遵循相应 Lua 运算符的语义(即,它可能会调用元方法)。
The value of op
must be one of the following constants:
op
的值必须是以下常量之一:
LUA_OPADD
: performs addition (+
)LUA_OPADD
:执行加法(+
)LUA_OPSUB
: performs subtraction (-
)LUA_OPSUB
:执行减法(-
)LUA_OPMUL
: performs multiplication (*
)LUA_OPMUL
:执行乘法(*
)LUA_OPDIV
: performs float division (/
)LUA_OPDIV
:执行浮点除法(/
)LUA_OPIDIV
: performs floor division (//
)LUA_OPIDIV
:执行向下取整除法(//
)LUA_OPMOD
: performs modulo (%
)LUA_OPMOD
:执行模运算(%
)LUA_OPPOW
: performs exponentiation (^
)LUA_OPPOW
:执行指数运算(^
)LUA_OPUNM
: performs mathematical negation (unary-
)LUA_OPUNM
:执行数学否定(一元-
)LUA_OPBNOT
: performs bitwise NOT (~
)LUA_OPBNOT
:执行按位非(~
)LUA_OPBAND
: performs bitwise AND (&
)LUA_OPBAND
:执行按位与(&
)LUA_OPBOR
: performs bitwise OR (|
)LUA_OPBOR
:执行按位或(|
)LUA_OPBXOR
: performs bitwise exclusive OR (~
)LUA_OPBXOR
:执行按位异或(~
)LUA_OPSHL
: performs left shift (<<
)LUA_OPSHL
:执行左移(<<
)LUA_OPSHR
: performs right shift (>>
)LUA_OPSHR
:执行右移(>>
)
lua_atpanic
[-0, +0, –]
lua_CFunction lua_atpanic (lua_State *L, lua_CFunction panicf);
Sets a new panic function and returns the old one (see §4.4).
设置一个新的 panic 函数并返回旧的 panic 函数(参见 §4.4)。
lua_call
[-(nargs+1), +nresults, e]
void lua_call (lua_State *L, int nargs, int nresults);
Calls a function. Like regular Lua calls, lua_call
respects the __call
metamethod. So, here the word “function” means any callable value.
调用一个函数。与常规的 Lua 调用一样, lua_call
尊重 __call
元方法。因此,这里“函数”一词表示任何可调用值。
To do a call you must use the following protocol: first, the function to be called is pushed onto the stack; then, the arguments to the call are pushed in direct order; that is, the first argument is pushed first. Finally you call lua_call
; nargs
is the number of arguments that you pushed onto the stack. When the function returns, all arguments and the function value are popped and the call results are pushed onto the stack. The number of results is adjusted to nresults
, unless nresults
is LUA_MULTRET
. In this case, all results from the function are pushed; Lua takes care that the returned values fit into the stack space, but it does not ensure any extra space in the stack. The function results are pushed onto the stack in direct order (the first result is pushed first), so that after the call the last result is on the top of the stack.
要进行调用,您必须使用以下协议:首先,将要调用的函数推送到栈上;然后,按顺序将调用参数推入;也就是说,首先将第一个参数推入。最后,您调用 lua_call
; nargs
是您推送到栈上的参数数量。当函数返回时,所有参数和函数值都会弹出,并将调用结果推送到栈上。结果数量调整为 nresults
,除非 nresults
为 LUA_MULTRET
。在这种情况下,将推送函数的所有结果;Lua 会确保返回值适合栈空间,但不会确保栈中有任何额外空间。函数结果按顺序推送到栈上(首先推送第一个结果),以便在调用之后最后一个结果位于栈顶部。
Any error while calling and running the function is propagated upwards (with a longjmp
).
在调用和运行函数时发生的任何错误都会向上传播(带有 longjmp
)。
The following example shows how the host program can do the equivalent to this Lua code:
下面的示例显示了宿主程序如何执行等同于此 Lua 代码的操作:
a = f("how", t.x, 14)
Here it is in C:
以下是 C 代码:
lua_getglobal(L, "f"); /* function to be called */
lua_pushliteral(L, "how"); /* 1st argument */
lua_getglobal(L, "t"); /* table to be indexed */
lua_getfield(L, -1, "x"); /* push result of t.x (2nd arg) */
lua_remove(L, -2); /* remove 't' from the stack */
lua_pushinteger(L, 14); /* 3rd argument */
lua_call(L, 3, 1); /* call 'f' with 3 arguments and 1 result */
lua_setglobal(L, "a"); /* set global 'a' */
Note that the code above is balanced: at its end, the stack is back to its original configuration. This is considered good programming practice.
请注意,上面的代码是平衡的:在代码的末尾,栈已恢复到其原始配置。这被认为是良好的编程实践。
lua_callk
[-(nargs + 1), +nresults, e]
void lua_callk (lua_State *L,
int nargs,
int nresults,
lua_KContext ctx,
lua_KFunction k);
This function behaves exactly like lua_call
, but allows the called function to yield (see §4.5).
此函数的行为与 lua_call
完全相同,但允许被调用的函数产生结果(参见 §4.5)。
lua_CFunction
typedef int (*lua_CFunction) (lua_State *L);
Type for C functions.
C 函数的类型。
In order to communicate properly with Lua, a C function must use the following protocol, which defines the way parameters and results are passed: a C function receives its arguments from Lua in its stack in direct order (the first argument is pushed first). So, when the function starts, lua_gettop(L)
returns the number of arguments received by the function. The first argument (if any) is at index 1 and its last argument is at index lua_gettop(L)
. To return values to Lua, a C function just pushes them onto the stack, in direct order (the first result is pushed first), and returns in C the number of results. Any other value in the stack below the results will be properly discarded by Lua. Like a Lua function, a C function called by Lua can also return many results.
为了与 Lua 正确通信,C 函数必须使用以下协议,该协议定义了传递参数和结果的方式:C 函数从 Lua 中按直接顺序接收其参数(第一个参数首先被推送)。因此,当函数启动时, lua_gettop(L)
返回函数接收到的参数数。第一个参数(如果有)位于索引 1 处,其最后一个参数位于索引 lua_gettop(L)
处。要向 Lua 返回值,C 函数只需按直接顺序将它们推送到栈上(第一个结果首先被推送),并在 C 中返回结果数。结果下方栈中的任何其他值都将被 Lua 正确丢弃。与 Lua 函数一样,Lua 调用的 C 函数也可以返回多个结果。
As an example, the following function receives a variable number of numeric arguments and returns their average and their sum:
例如,以下函数接收可变数量的数字参数并返回它们的平均值和总和:
static int foo (lua_State *L) {
int n = lua_gettop(L); /* number of arguments */
lua_Number sum = 0.0;
int i;
for (i = 1; i <= n; i++) {
if (!lua_isnumber(L, i)) {
lua_pushliteral(L, "incorrect argument");
lua_error(L);
}
sum += lua_tonumber(L, i);
}
lua_pushnumber(L, sum/n); /* first result */
lua_pushnumber(L, sum); /* second result */
return 2; /* number of results */
}
lua_checkstack
[-0, +0, –]
int lua_checkstack (lua_State *L, int n);
Ensures that the stack has space for at least n
extra elements, that is, that you can safely push up to n
values into it. It returns false if it cannot fulfill the request, either because it would cause the stack to be greater than a fixed maximum size (typically at least several thousand elements) or because it cannot allocate memory for the extra space. This function never shrinks the stack; if the stack already has space for the extra elements, it is left unchanged.
确保栈至少有 n
个额外的元素空间,也就是说,您可以安全地将最多 n
个值推入其中。如果无法满足请求,则返回 false,原因可能是这会导致栈大于固定的最大大小(通常至少有几千个元素),或者无法为额外空间分配内存。此函数绝不会缩小栈;如果栈已经为额外元素留有空间,则保持不变。
lua_close
[-0, +0, –]
void lua_close (lua_State *L);
Close all active to-be-closed variables in the main thread, release all objects in the given Lua state (calling the corresponding garbage-collection metamethods, if any), and frees all dynamic memory used by this state.
关闭主线程中所有处于活动状态的待关闭变量,释放给定 Lua 状态中的所有对象(如果存在,则调用相应的垃圾回收元方法),并释放此状态使用的所有动态内存。
On several platforms, you may not need to call this function, because all resources are naturally released when the host program ends. On the other hand, long-running programs that create multiple states, such as daemons or web servers, will probably need to close states as soon as they are not needed.
在多个平台上,您可能不需要调用此函数,因为当宿主程序结束时,所有资源都会自然释放。另一方面,创建多个状态的长期运行程序(例如守护程序或 Web 服务器)可能需要在不再需要时关闭状态。
lua_closeslot
[-0, +0, e]
void lua_closeslot (lua_State *L, int index);
Close the to-be-closed slot at the given index and set its value to nil. The index must be the last index previously marked to be closed (see lua_toclose
) that is still active (that is, not closed yet).
关闭给定索引处的待关闭槽,并将其值设置为 nil。索引必须是先前标记为待关闭的最后一个索引(请参阅 lua_toclose
),并且仍然处于活动状态(即尚未关闭)。
A __close
metamethod cannot yield when called through this function.
通过此函数调用时, __close
元方法不能产生结果。
(This function was introduced in release 5.4.3.)
(此函数在版本 5.4.3 中引入。)
lua_closethread
[-0, +?, –]
int lua_closethread (lua_State *L, lua_State *from);
Resets a thread, cleaning its call stack and closing all pending to-be-closed variables. Returns a status code: LUA_OK
for no errors in the thread (either the original error that stopped the thread or errors in closing methods), or an error status otherwise. In case of error, leaves the error object on the top of the stack.
重置线程,清除其调用栈并关闭所有待关闭变量。返回状态代码: LUA_OK
表示线程中没有错误(导致线程停止的原始错误或关闭方法中的错误),否则表示错误状态。如果发生错误,则将错误对象保留在栈顶部。
The parameter from
represents the coroutine that is resetting L
. If there is no such coroutine, this parameter can be NULL
.
参数 from
表示正在重置 L
的协程。如果不存在此类协程,则此参数可以是 NULL
。
(This function was introduced in release 5.4.6.)
(此函数在版本 5.4.6 中引入。)
lua_compare
[-0, +0, e]
int lua_compare (lua_State *L, int index1, int index2, int op);
Compares two Lua values. Returns 1 if the value at index index1
satisfies op
when compared with the value at index index2
, following the semantics of the corresponding Lua operator (that is, it may call metamethods). Otherwise returns 0. Also returns 0 if any of the indices is not valid.
比较两个 Lua 值。如果索引 index1
处的值满足与索引 index2
处的值比较后的 op
,则返回 1,遵循相应 Lua 运算符的语义(即,它可能会调用元方法)。否则返回 0。如果任何索引无效,也返回 0。
The value of op
must be one of the following constants:
op
的值必须是以下常量之一:
LUA_OPEQ
: compares for equality (==
)LUA_OPEQ
:比较相等(==
)LUA_OPLT
: compares for less than (<
)LUA_OPLT
:比较小于(<
)LUA_OPLE
: compares for less or equal (<=
)LUA_OPLE
:比较小于或等于(<=
)
lua_concat
[-n, +1, e]
void lua_concat (lua_State *L, int n);
Concatenates the n
values at the top of the stack, pops them, and leaves the result on the top. If n
is 1, the result is the single value on the stack (that is, the function does nothing); if n
is 0, the result is the empty string. Concatenation is performed following the usual semantics of Lua (see §3.4.6).
连接栈顶的 n
个值,弹出它们,并将结果留在栈顶。如果 n
为 1,则结果是栈上的单个值(即,该函数不执行任何操作);如果 n
为 0,则结果为空字符串。连接按照 Lua 的通常语义执行(参见 §3.4.6)。
lua_copy
[-0, +0, –]
void lua_copy (lua_State *L, int fromidx, int toidx);
Copies the element at index fromidx
into the valid index toidx
, replacing the value at that position. Values at other positions are not affected.
将索引 fromidx
处的元素复制到有效索引 toidx
中,替换该位置的值。其他位置的值不受影响。
lua_createtable
[-0, +1, m]
void lua_createtable (lua_State *L, int narr, int nrec);
Creates a new empty table and pushes it onto the stack. Parameter narr
is a hint for how many elements the table will have as a sequence; parameter nrec
is a hint for how many other elements the table will have. Lua may use these hints to preallocate memory for the new table. This preallocation may help performance when you know in advance how many elements the table will have. Otherwise you can use the function lua_newtable
.
创建一个新的空表并将其压入栈。参数 narr
是一个提示,表示该表将作为序列有多少个元素;参数 nrec
是一个提示,表示该表将有多少个其他元素。Lua 可能会使用这些提示为新表预分配内存。当您预先知道该表将有多少个元素时,这种预分配可能有助于提高性能。否则,您可以使用函数 lua_newtable
。
lua_dump
[-0, +0, –]
int lua_dump (lua_State *L,
lua_Writer writer,
void *data,
int strip);
Dumps a function as a binary chunk. Receives a Lua function on the top of the stack and produces a binary chunk that, if loaded again, results in a function equivalent to the one dumped. As it produces parts of the chunk, lua_dump
calls function writer
(see lua_Writer
) with the given data
to write them.
将函数转储为二进制块。在栈顶部接收一个 Lua 函数,并生成一个二进制块,如果再次加载,则会生成一个等效于转储函数的函数。由于它生成块的部分, lua_dump
使用给定的 data
调用函数 writer
(请参阅 lua_Writer
)来写入它们。
If strip
is true, the binary representation may not include all debug information about the function, to save space.
如果 strip
为 true,则二进制表示可能不包含有关函数的所有调试信息,以节省空间。
The value returned is the error code returned by the last call to the writer; 0 means no errors.
返回的值是写入器最后一次调用返回的错误代码;0 表示没有错误。
This function does not pop the Lua function from the stack.
此函数不会从栈中弹出 Lua 函数。
lua_error
[-1, +0, v]
int lua_error (lua_State *L);
Raises a Lua error, using the value on the top of the stack as the error object. This function does a long jump, and therefore never returns (see luaL_error
).
引发 Lua 错误,使用栈顶部的值作为错误对象。此函数执行远跳转,因此从不返回(请参阅 luaL_error
)。
lua_gc
[-0, +0, –]
int lua_gc (lua_State *L, int what, ...);
Controls the garbage collector.
控制垃圾回收器。
This function performs several tasks, according to the value of the parameter what
. For options that need extra arguments, they are listed after the option.
此函数根据参数 what
的值执行多个任务。对于需要额外参数的选项,它们在选项后列出。
LUA_GCCOLLECT
: Performs a full garbage-collection cycle.LUA_GCCOLLECT
:执行完整的垃圾回收周期。LUA_GCSTOP
: Stops the garbage collector.LUA_GCSTOP
:停止垃圾回收器。LUA_GCRESTART
: Restarts the garbage collector.LUA_GCRESTART
:重新启动垃圾回收器。LUA_GCCOUNT
: Returns the current amount of memory (in Kbytes) in use by Lua.LUA_GCCOUNT
:返回 Lua 使用的当前内存量(以 KB 为单位)。LUA_GCCOUNTB
: Returns the remainder of dividing the current amount of bytes of memory in use by Lua by 1024.LUA_GCCOUNTB
:返回 Lua 使用的当前内存字节数除以 1024 的余数。LUA_GCSTEP
(int stepsize)
: Performs an incremental step of garbage collection, corresponding to the allocation ofstepsize
Kbytes.LUA_GCSTEP
(int stepsize)
:执行垃圾回收的增量步骤,对应于stepsize
KB 的分配。LUA_GCISRUNNING
: Returns a boolean that tells whether the collector is running (i.e., not stopped).LUA_GCISRUNNING
:返回一个布尔值,指示回收器是否正在运行(即未停止)。LUA_GCINC
(int pause, int stepmul, stepsize): Changes the collector to incremental mode with the given parameters (see §2.5.1). Returns the previous mode (LUA_GCGEN
orLUA_GCINC
).LUA_GCINC
(int pause, int stepmul, stepsize):使用给定参数将回收器更改为增量模式(请参阅 §2.5.1)。返回上一个模式(LUA_GCGEN
或LUA_GCINC
)。LUA_GCGEN
(int minormul, int majormul): Changes the collector to generational mode with the given parameters (see §2.5.2). Returns the previous mode (LUA_GCGEN
orLUA_GCINC
).LUA_GCGEN
(int minormul, int majormul):使用给定参数将回收器更改为代际模式(请参阅 §2.5.2)。返回上一个模式(LUA_GCGEN
或LUA_GCINC
)。
For more details about these options, see collectgarbage
.
有关这些选项的更多详细信息,请参阅 collectgarbage
。
This function should not be called by a finalizer.
此函数不应由终结器调用。
lua_getallocf
[-0, +0, –]
lua_Alloc lua_getallocf (lua_State *L, void **ud);
Returns the memory-allocation function of a given state. If ud
is not NULL
, Lua stores in *ud
the opaque pointer given when the memory-allocator function was set.
返回给定状态的内存分配函数。如果 ud
不为 NULL
,Lua 会将设置内存分配器函数时给出的不透明指针存储在 *ud
中。
lua_getfield
[-0, +1, e]
int lua_getfield (lua_State *L, int index, const char *k);
Pushes onto the stack the value t[k]
, where t
is the value at the given index. As in Lua, this function may trigger a metamethod for the “index” event (see §2.4).
将值 t[k]
压入栈,其中 t
是给定索引处的值。与 Lua 中一样,此函数可能会触发“index”事件的元方法(请参阅 §2.4)。
Returns the type of the pushed value.
返回压入的值的类型。
lua_getextraspace
[-0, +0, –]
void *lua_getextraspace (lua_State *L);
Returns a pointer to a raw memory area associated with the given Lua state. The application can use this area for any purpose; Lua does not use it for anything.
返回与给定的 Lua 状态相关联的原始内存区域的指针。应用程序可以将此区域用于任何目的;Lua 不会将其用于任何目的。
Each new thread has this area initialized with a copy of the area of the main thread.
每个新线程都将此区域初始化为对主线程区域的副本。
By default, this area has the size of a pointer to void, but you can recompile Lua with a different size for this area. (See LUA_EXTRASPACE
in luaconf.h
.)
默认情况下,此区域的大小为指向 void 的指针的大小,但您可以使用不同的区域大小重新编译 Lua。(请参阅 LUA_EXTRASPACE
中的 luaconf.h
。)
lua_getglobal
[-0, +1, e]
int lua_getglobal (lua_State *L, const char *name);
Pushes onto the stack the value of the global name
. Returns the type of that value.
将全局 name
的值压入栈。返回该值的数据类型。
lua_geti
[-0, +1, e]
int lua_geti (lua_State *L, int index, lua_Integer i);
Pushes onto the stack the value t[i]
, where t
is the value at the given index. As in Lua, this function may trigger a metamethod for the “index” event (see §2.4).
将值 t[i]
压入栈,其中 t
是给定索引处的值。与 Lua 中一样,此函数可能会触发“index”事件的元方法(请参阅 §2.4)。
Returns the type of the pushed value.
返回压入值的数据类型。
lua_getmetatable
[-0, +(0|1), –]
int lua_getmetatable (lua_State *L, int index);
If the value at the given index has a metatable, the function pushes that metatable onto the stack and returns 1. Otherwise, the function returns 0 and pushes nothing on the stack.
如果给定索引处的值具有元表,则该函数将该元表压入栈并返回 1。否则,该函数返回 0 且不将任何内容压入栈。
lua_gettable
[-1, +1, e]
int lua_gettable (lua_State *L, int index);
Pushes onto the stack the value t[k]
, where t
is the value at the given index and k
is the value on the top of the stack.
将值 t[k]
压入栈,其中t
是给定索引处的值,k
是栈顶部的值。
This function pops the key from the stack, pushing the resulting value in its place. As in Lua, this function may trigger a metamethod for the “index” event (see §2.4).
此函数从栈中弹出键,将其替换为结果值。与 Lua 中一样,此函数可能会触发“index”事件的元方法(请参阅 §2.4)。
Returns the type of the pushed value.
返回压入值的数据类型。
lua_gettop
[-0, +0, –]
int lua_gettop (lua_State *L);
Returns the index of the top element in the stack. Because indices start at 1, this result is equal to the number of elements in the stack; in particular, 0 means an empty stack.
返回栈顶元素的索引。由于索引从 1 开始,因此此结果等于栈中的元素数量;特别是,0 表示栈为空。
lua_getiuservalue
[-0, +1, –]
int lua_getiuservalue (lua_State *L, int index, int n);
Pushes onto the stack the n
-th user value associated with the full userdata at the given index and returns the type of the pushed value.
将第 n
个与给定索引处的完整用户数据关联的用户值推入栈,并返回所推入值的类型。
If the userdata does not have that value, pushes nil and returns LUA_TNONE
.
如果用户数据没有该值,则推入 nil 并返回 LUA_TNONE
。
lua_insert
[-1, +1, –]
void lua_insert (lua_State *L, int index);
Moves the top element into the given valid index, shifting up the elements above this index to open space. This function cannot be called with a pseudo-index, because a pseudo-index is not an actual stack position.
将栈顶元素移动到给定的有效索引中,将该索引以上的元素向上移动以腾出空间。此函数不能用伪索引调用,因为伪索引不是实际的栈位置。
lua_Integer
typedef ... lua_Integer;
The type of integers in Lua.
Lua 中整数的类型。
By default this type is long long
, (usually a 64-bit two-complement integer), but that can be changed to long
or int
(usually a 32-bit two-complement integer). (See LUA_INT_TYPE
in luaconf.h
.)
默认情况下,此类型为 long long
,(通常为 64 位二进制补码整数),但可以将其更改为 long
或 int
(通常为 32 位二进制补码整数)。(请参阅 luaconf.h
中的 LUA_INT_TYPE
。)
Lua also defines the constants LUA_MININTEGER
and LUA_MAXINTEGER
, with the minimum and the maximum values that fit in this type.
Lua 还定义了常量 LUA_MININTEGER
和 LUA_MAXINTEGER
,其中包含适合此类型的最小值和最大值。
lua_isboolean
[-0, +0, –]
int lua_isboolean (lua_State *L, int index);
Returns 1 if the value at the given index is a boolean, and 0 otherwise.
如果给定索引处的值是布尔值,则返回 1,否则返回 0。
lua_iscfunction
[-0, +0, –]
int lua_iscfunction (lua_State *L, int index);
Returns 1 if the value at the given index is a C function, and 0 otherwise.
如果给定索引处的值是 C 函数,则返回 1,否则返回 0。
lua_isfunction
[-0, +0, –]
int lua_isfunction (lua_State *L, int index);
Returns 1 if the value at the given index is a function (either C or Lua), and 0 otherwise.
如果给定索引处的值是函数(C 或 Lua),则返回 1,否则返回 0。
lua_isinteger
[-0, +0, –]
int lua_isinteger (lua_State *L, int index);
Returns 1 if the value at the given index is an integer (that is, the value is a number and is represented as an integer), and 0 otherwise.
如果给定索引处的值是整数(即该值是一个数字并且表示为整数),则返回 1,否则返回 0。
lua_islightuserdata
[-0, +0, –]
int lua_islightuserdata (lua_State *L, int index);
Returns 1 if the value at the given index is a light userdata, and 0 otherwise.
如果给定索引处的值是轻用户数据,则返回 1,否则返回 0。
lua_isnil
[-0, +0, –]
int lua_isnil (lua_State *L, int index);
Returns 1 if the value at the given index is nil, and 0 otherwise.
如果给定索引处的值为 nil,则返回 1,否则返回 0。
lua_isnone
[-0, +0, –]
int lua_isnone (lua_State *L, int index);
Returns 1 if the given index is not valid, and 0 otherwise.
如果给定索引无效,则返回 1,否则返回 0。
lua_isnoneornil
[-0, +0, –]
int lua_isnoneornil (lua_State *L, int index);
Returns 1 if the given index is not valid or if the value at this index is nil, and 0 otherwise.
如果给定的索引无效或此索引处的值为 nil,则返回 1,否则返回 0。
lua_isnumber
[-0, +0, –]
int lua_isnumber (lua_State *L, int index);
Returns 1 if the value at the given index is a number or a string convertible to a number, and 0 otherwise.
如果给定索引处的值是数字或可转换为数字的字符串,则返回 1,否则返回 0。
lua_isstring
[-0, +0, –]
int lua_isstring (lua_State *L, int index);
Returns 1 if the value at the given index is a string or a number (which is always convertible to a string), and 0 otherwise.
如果给定索引处的值是字符串或数字(始终可转换为字符串),则返回 1,否则返回 0。
lua_istable
[-0, +0, –]
int lua_istable (lua_State *L, int index);
Returns 1 if the value at the given index is a table, and 0 otherwise.
如果给定索引处的值是表,则返回 1,否则返回 0。
lua_isthread
[-0, +0, –]
int lua_isthread (lua_State *L, int index);
Returns 1 if the value at the given index is a thread, and 0 otherwise.
如果给定索引处的值是线程,则返回 1,否则返回 0。
lua_isuserdata
[-0, +0, –]
int lua_isuserdata (lua_State *L, int index);
Returns 1 if the value at the given index is a userdata (either full or light), and 0 otherwise.
如果给定索引处的值是用户数据(完整或精简),则返回 1,否则返回 0。
lua_isyieldable
[-0, +0, –]
int lua_isyieldable (lua_State *L);
Returns 1 if the given coroutine can yield, and 0 otherwise.
如果给定的协程可以生成,则返回 1,否则返回 0。
lua_KContext
typedef ... lua_KContext;
typedef ... lua_KContext;
The type for continuation-function contexts. It must be a numeric type. This type is defined as intptr_t
when intptr_t
is available, so that it can store pointers too. Otherwise, it is defined as ptrdiff_t
.
用于延续函数上下文的类型。它必须是数值类型。当 intptr_t
可用时,此类型定义为 intptr_t
,以便它也可以存储指针。否则,它被定义为 ptrdiff_t
。
lua_KFunction
typedef int (*lua_KFunction) (lua_State *L, int status, lua_KContext ctx);
Type for continuation functions (see §4.5).
用于延续函数的类型(参见 §4.5)。
lua_len
[-0, +1, e]
void lua_len (lua_State *L, int index);
Returns the length of the value at the given index. It is equivalent to the ‘#
’ operator in Lua (see §3.4.7) and may trigger a metamethod for the “length” event (see §2.4). The result is pushed on the stack.
返回给定索引处的值的长度。它等同于 Lua 中的“ #
”运算符(参见 §3.4.7),并且可能会触发“长度”事件的元方法(参见 §2.4)。结果被压入栈。
lua_load
[-0, +1, –]
int lua_load (lua_State *L,
lua_Reader reader,
void *data,
const char *chunkname,
const char *mode);
Loads a Lua chunk without running it. If there are no errors, lua_load
pushes the compiled chunk as a Lua function on top of the stack. Otherwise, it pushes an error message.
在不运行的情况下加载一个 Lua 块。如果没有错误, lua_load
将编译的块作为 Lua 函数压入栈顶。否则,它将压入一条错误消息。
The lua_load
function uses a user-supplied reader
function to read the chunk (see lua_Reader
). The data
argument is an opaque value passed to the reader function.
lua_load
函数使用用户提供的 reader
函数来读取块(参见 lua_Reader
)。 data
参数是一个传递给读取器函数的不透明值。
The chunkname
argument gives a name to the chunk, which is used for error messages and in debug information (see §4.7).
chunkname
参数为块提供一个名称,该名称用于错误消息和调试信息(参见 §4.7)。
lua_load
automatically detects whether the chunk is text or binary and loads it accordingly (see program luac
). The string mode
works as in function load
, with the addition that a NULL
value is equivalent to the string “bt
”.
lua_load
会自动检测块是文本还是二进制,并相应地加载它(参见程序 luac
)。字符串 mode
的作用与函数 load
中的作用相同,此外, NULL
值等同于字符串“ bt
”。
lua_load
uses the stack internally, so the reader function must always leave the stack unmodified when returning.
lua_load
在内部使用栈,因此读取器函数在返回时必须始终保持栈不变。
lua_load
can return LUA_OK
, LUA_ERRSYNTAX
, or LUA_ERRMEM
. The function may also return other values corresponding to errors raised by the read function (see §4.4.1).
lua_load
可以返回 LUA_OK
、 LUA_ERRSYNTAX
或 LUA_ERRMEM
。该函数还可以返回与读取函数引发的错误相对应的其他值(参见 §4.4.1)。
If the resulting function has upvalues, its first upvalue is set to the value of the global environment stored at index LUA_RIDX_GLOBALS
in the registry (see §4.3). When loading main chunks, this upvalue will be the _ENV
variable (see §2.2). Other upvalues are initialized with nil.
如果结果函数具有上值,则其第一个上值将设置为存储在注册表中索引为 LUA_RIDX_GLOBALS
的全局环境的值(参见 §4.3)。加载主块时,此上值将是 _ENV
变量(参见 §2.2)。其他上值将初始化为 nil。
lua_newstate
[-0, +0, –]
lua_State *lua_newstate (lua_Alloc f, void *ud);
Creates a new independent state and returns its main thread. Returns NULL
if it cannot create the state (due to lack of memory). The argument f
is the allocator function; Lua will do all memory allocation for this state through this function (see lua_Alloc
). The second argument, ud
, is an opaque pointer that Lua passes to the allocator in every call.
创建一个新的独立状态并返回其主线程。如果无法创建状态(由于内存不足),则返回 NULL
。参数 f
是分配器函数;Lua 将通过此函数为该状态执行所有内存分配(参见 lua_Alloc
)。第二个参数 ud
是一个不透明指针,Lua 在每次调用中都会将其传递给分配器。
lua_newtable
[-0, +1, m]
void lua_newtable (lua_State *L);
Creates a new empty table and pushes it onto the stack. It is equivalent to lua_createtable(L, 0, 0)
.
创建一个新的空表并将其压入栈。它等效于 lua_createtable(L, 0, 0)
。
lua_newthread
[-0, +1, m]
lua_State *lua_newthread (lua_State *L);
Creates a new thread, pushes it on the stack, and returns a pointer to a lua_State
that represents this new thread. The new thread returned by this function shares with the original thread its global environment, but has an independent execution stack.
创建一个新线程,将其压入栈,并返回一个表示此新线程的 lua_State
的指针。此函数返回的新线程与其原始线程共享其全局环境,但具有独立的执行栈。
Threads are subject to garbage collection, like any Lua object.
线程受垃圾回收的影响,就像任何 Lua 对象一样。
lua_newuserdatauv
[-0, +1, m]
void *lua_newuserdatauv (lua_State *L, size_t size, int nuvalue);
This function creates and pushes on the stack a new full userdata, with nuvalue
associated Lua values, called user values
, plus an associated block of raw memory with size
bytes. (The user values can be set and read with the functions lua_setiuservalue
and lua_getiuservalue
.)
此函数创建并向栈中推送一个新的完整用户数据,其中包含 nuvalue
个关联的 Lua 值,称为 user values
,外加一个包含 size
个字节的关联原始内存块。(可以使用函数 lua_setiuservalue
和 lua_getiuservalue
设置和读取用户值。)
The function returns the address of the block of memory. Lua ensures that this address is valid as long as the corresponding userdata is alive (see §2.5). Moreover, if the userdata is marked for finalization (see §2.5.3), its address is valid at least until the call to its finalizer.
该函数返回内存块的地址。Lua 确保只要相应用户数据存在,此地址就是有效的(请参阅 §2.5)。此外,如果用户数据被标记为要完成(请参阅 §2.5.3),则其地址至少在调用其完成函数之前是有效的。
lua_next
[-1, +(2|0), v]
int lua_next (lua_State *L, int index);
Pops a key from the stack, and pushes a key–value pair from the table at the given index, the “next” pair after the given key. If there are no more elements in the table, then lua_next
returns 0 and pushes nothing.
从栈中弹出键,并从给定索引处的表中推送键值对,即给定键之后的“下一个”对。如果表中没有更多元素,则 lua_next
返回 0 且不推送任何内容。
A typical table traversal looks like this:
典型的表遍历如下所示:
/* table is in the stack at index 't' */
lua_pushnil(L); /* first key */
while (lua_next(L, t) != 0) {
/* uses 'key' (at index -2) and 'value' (at index -1) */
printf("%s - %s\n",
lua_typename(L, lua_type(L, -2)),
lua_typename(L, lua_type(L, -1)));
/* removes 'value'; keeps 'key' for next iteration */
lua_pop(L, 1);
}
While traversing a table, avoid calling lua_tolstring
directly on a key, unless you know that the key is actually a string. Recall that lua_tolstring
may change the value at the given index; this confuses the next call to lua_next
.
在遍历一个表时,避免直接对键调用 lua_tolstring
,除非你知道该键实际上是一个字符串。回想一下, lua_tolstring
可能会改变给定索引处的键值;这会混淆对 lua_next
的下一个调用。
This function may raise an error if the given key is neither nil nor present in the table. See function next
for the caveats of modifying the table during its traversal.
如果给定的键既不是nil也不是表中存在,则此函数可能会引发错误。有关在遍历表期间修改表时的注意事项,请参阅函数 next
。
lua_Number
typedef ... lua_Number;
The type of floats in Lua.
Lua 中浮点数的类型。
By default this type is double, but that can be changed to a single float or a long double. (See LUA_FLOAT_TYPE
in luaconf.h
.)
默认情况下,此类型为双精度,但可以将其更改为单精度浮点数或长双精度浮点数。(请参阅 LUA_FLOAT_TYPE
中的 luaconf.h
。)
lua_numbertointeger
int lua_numbertointeger (lua_Number n, lua_Integer *p);
Tries to convert a Lua float to a Lua integer; the float n
must have an integral value. If that value is within the range of Lua integers, it is converted to an integer and assigned to *p
. The macro results in a boolean indicating whether the conversion was successful. (Note that this range test can be tricky to do correctly without this macro, due to rounding.)
尝试将 Lua 浮点数转换为 Lua 整数;浮点数 n
必须具有整数值。如果该值在 Lua 整数的范围内,则将其转换为整数并赋值给 *p
。宏的结果是一个布尔值,指示转换是否成功。(请注意,由于舍入,如果没有此宏,此范围测试可能很难正确执行。)
This macro may evaluate its arguments more than once.
此宏可能会多次计算其参数。
lua_pcall
[-(nargs + 1), +(nresults|1), –]
int lua_pcall (lua_State *L, int nargs, int nresults, int msgh);
Calls a function (or a callable object) in protected mode.
以受保护模式调用函数(或可调用对象)。
Both nargs
and nresults
have the same meaning as in lua_call
. If there are no errors during the call, lua_pcall
behaves exactly like lua_call
. However, if there is any error, lua_pcall
catches it, pushes a single value on the stack (the error object), and returns an error code. Like lua_call
, lua_pcall
always removes the function and its arguments from the stack.
nargs
和 nresults
的含义与 lua_call
中的含义相同。如果调用期间没有错误,则 lua_pcall
的行为与 lua_call
完全相同。但是,如果有任何错误, lua_pcall
会捕获它,将单个值压入栈(错误对象),并返回错误代码。与 lua_call
一样, lua_pcall
始终从栈中删除函数及其参数。
If msgh
is 0, then the error object returned on the stack is exactly the original error object. Otherwise, msgh
is the stack index of a message handler. (This index cannot be a pseudo-index.) In case of runtime errors, this handler will be called with the error object and its return value will be the object returned on the stack by lua_pcall
.
如果 msgh
为 0,则栈上返回的错误对象就是原始错误对象。否则, msgh
是消息处理程序的栈索引。(此索引不能是伪索引。)在运行时错误的情况下,此处理程序将使用错误对象调用,其返回值将是 lua_pcall
在栈上返回的对象。
Typically, the message handler is used to add more debug information to the error object, such as a stack traceback. Such information cannot be gathered after the return of lua_pcall
, since by then the stack has unwound.
通常,消息处理程序用于向错误对象添加更多调试信息,例如栈回溯。此类信息无法在 lua_pcall
返回后收集,因为那时栈已展开。
The lua_pcall
function returns one of the following status codes: LUA_OK
, LUA_ERRRUN
, LUA_ERRMEM
, or LUA_ERRERR
.
lua_pcall
函数返回以下状态代码之一: LUA_OK
、 LUA_ERRRUN
、 LUA_ERRMEM
或 LUA_ERRERR
。
lua_pcallk
[-(nargs + 1), +(nresults|1), –]
int lua_pcallk (lua_State *L,
int nargs,
int nresults,
int msgh,
lua_KContext ctx,
lua_KFunction k);
This function behaves exactly like lua_pcall
, except that it allows the called function to yield (see §4.5).
此函数的行为与 lua_pcall
完全相同,但它允许被调用的函数产生(参见 §4.5)。
lua_pop
[-n, +0, e]
void lua_pop (lua_State *L, int n);
Pops n
elements from the stack. It is implemented as a macro over lua_settop
.
从栈中弹出 n
个元素。它作为 lua_settop
上的宏实现。
lua_pushboolean
[-0, +1, –]
void lua_pushboolean (lua_State *L, int b);
Pushes a boolean value with value b
onto the stack.
将布尔值 b
压入栈中。
lua_pushcclosure
[-n, +1, m]
void lua_pushcclosure (lua_State *L, lua_CFunction fn, int n);
Pushes a new C closure onto the stack. This function receives a pointer to a C function and pushes onto the stack a Lua value of type function
that, when called, invokes the corresponding C function. The parameter n
tells how many upvalues this function will have (see §4.2).
将新的 C 闭包压入栈中。此函数接收一个指向 C 函数的指针,并将类型为 function
的 Lua 值压入栈中,当调用时,将调用相应的 C 函数。参数 n
指示此函数将具有多少个上值(请参阅 §4.2)。
Any function to be callable by Lua must follow the correct protocol to receive its parameters and return its results (see lua_CFunction
).
任何可由 Lua 调用的函数都必须遵循正确的协议来接收其参数并返回其结果(请参阅 lua_CFunction
)。
When a C function is created, it is possible to associate some values with it, the so called upvalues; these upvalues are then accessible to the function whenever it is called. This association is called a C closure (see §4.2). To create a C closure, first the initial values for its upvalues must be pushed onto the stack. (When there are multiple upvalues, the first value is pushed first.) Then lua_pushcclosure
is called to create and push the C function onto the stack, with the argument n
telling how many values will be associated with the function. lua_pushcclosure
also pops these values from the stack.
当创建一个 C 函数时,可以将一些值与之关联,即所谓的上值;然后,无论何时调用该函数,都可以访问这些上值。这种关联称为 C 闭包(参见 §4.2)。要创建 C 闭包,首先必须将上值的初始值压入栈。(当有多个上值时,首先压入第一个值。)然后调用 lua_pushcclosure
以创建 C 函数并将其压入栈,参数 n
告诉将有多少个值与该函数关联。 lua_pushcclosure
还从栈中弹出这些值。
The maximum value for n
is 255.
n
的最大值为 255。
When n
is zero, this function creates a light C function, which is just a pointer to the C function. In that case, it never raises a memory error.
当 n
为零时,此函数创建一个轻量级 C 函数,它只是一个指向 C 函数的指针。在这种情况下,它绝不会引发内存错误。
lua_pushcfunction
[-0, +1, –]
void lua_pushcfunction (lua_State *L, lua_CFunction f);
Pushes a C function onto the stack. This function is equivalent to lua_pushcclosure
with no upvalues.
将 C 函数压入栈。此函数等同于没有上值的 lua_pushcclosure
。
lua_pushfstring
[-0, +1, v]
const char *lua_pushfstring (lua_State *L, const char *fmt, ...);
Pushes onto the stack a formatted string and returns a pointer to this string (see §4.1.3). It is similar to the ISO C function sprintf
, but has two important differences. First, you do not have to allocate space for the result; the result is a Lua string and Lua takes care of memory allocation (and deallocation, through garbage collection). Second, the conversion specifiers are quite restricted. There are no flags, widths, or precisions. The conversion specifiers can only be ‘%%
’ (inserts the character ‘%
’), ‘%s
’ (inserts a zero-terminated string, with no size restrictions), ‘%f
’ (inserts a lua_Number
), ‘%I
’ (inserts a lua_Integer
), ‘%p
’ (inserts a pointer), ‘%d
’ (inserts an int
), ‘%c
’ (inserts an int
as a one-byte character), and ‘%U
’ (inserts a long int
as a UTF-8 byte sequence).
将格式化字符串推送到栈并返回指向此字符串的指针(请参阅 §4.1.3)。它类似于 ISO C 函数 sprintf
,但有两个重要区别。首先,您不必为结果分配空间;结果是 Lua 字符串,Lua 会负责内存分配(以及通过垃圾回收进行的释放)。其次,转换说明符受到相当大的限制。没有标志、宽度或精度。转换说明符只能是 ’ %%
‘(插入字符 ’ %
‘)、’ %s
‘(插入零终止字符串,无大小限制)、’ %f
‘(插入 lua_Number
)、’ %I
‘(插入 lua_Integer
)、’ %p
‘(插入指针)、’ %d
‘(插入 int
)、’ %c
‘(插入 int
作为单字节字符)和 ’ %U
‘(插入 long int
作为 UTF-8 字节序列)。
This function may raise errors due to memory overflow or an invalid conversion specifier.
此函数可能会因内存溢出或无效转换说明符而引发错误。
lua_pushglobaltable
[-0, +1, –]
void lua_pushglobaltable (lua_State *L);
Pushes the global environment onto the stack.
将全局环境推送到栈。
lua_pushinteger
[-0, +1, –]
void lua_pushinteger (lua_State *L, lua_Integer n);
Pushes an integer with value n
onto the stack.
将一个值为 n
的整数压入栈。
lua_pushlightuserdata
[-0, +1, –]
void lua_pushlightuserdata (lua_State *L, void *p);
Pushes a light userdata onto the stack.
将轻用户数据推入栈。
Userdata represent C values in Lua. A light userdata represents a pointer, a void*
. It is a value (like a number): you do not create it, it has no individual metatable, and it is not collected (as it was never created). A light userdata is equal to “any” light userdata with the same C address.
用户数据表示 Lua 中的 C 值。轻用户数据表示一个指针,即 void*
。它是一个值(如数字):您不会创建它,它没有单独的元表,并且不会被收集(因为它从未被创建)。轻用户数据等于具有相同 C 地址的“任何”轻用户数据。
lua_pushliteral
[-0, +1, m]
const char *lua_pushliteral (lua_State *L, const char *s);
This macro is equivalent to lua_pushstring
, but should be used only when s
is a literal string. (Lua may optimize this case.)
此宏等效于 lua_pushstring
,但仅当 s
是一个字符串文字时才应使用它。(Lua 可以优化这种情况。)
lua_pushlstring
[-0, +1, m]
const char *lua_pushlstring (lua_State *L, const char *s, size_t len);
Pushes the string pointed to by s
with size len
onto the stack. Lua will make or reuse an internal copy of the given string, so the memory at s
can be freed or reused immediately after the function returns. The string can contain any binary data, including embedded zeros.
将由 s
指向的字符串(大小为 len
)推入栈。Lua 将创建或重用给定字符串的内部副本,因此在函数返回后可以立即释放或重用 s
处的内存。该字符串可以包含任何二进制数据,包括嵌入的零。
Returns a pointer to the internal copy of the string (see §4.1.3).
返回字符串的内部副本的指针(请参阅 §4.1.3)。
lua_pushnil
[-0, +1, –]
void lua_pushnil (lua_State *L);
Pushes a nil value onto the stack.
将 nil 值推入栈。
lua_pushnumber
[-0, +1, –]
void lua_pushnumber (lua_State *L, lua_Number n);
Pushes a float with value n
onto the stack.
将值 n
的浮点数推入栈。
lua_pushstring
[-0, +1, m]
const char *lua_pushstring (lua_State *L, const char *s);
Pushes the zero-terminated string pointed to by s
onto the stack. Lua will make or reuse an internal copy of the given string, so the memory at s
can be freed or reused immediately after the function returns.
将 s
指向的以零结尾的字符串推入栈。Lua 将创建或重用给定字符串的内部副本,因此在函数返回后可以立即释放或重用 s
处的内存。
Returns a pointer to the internal copy of the string (see §4.1.3).
返回字符串的内部副本的指针(参见 §4.1.3)。
If s
is NULL
, pushes nil and returns NULL
.
如果 s
是 NULL
,则推送 nil 并返回 NULL
。
lua_pushthread
[-0, +1, –]
int lua_pushthread (lua_State *L);
Pushes the thread represented by L
onto the stack. Returns 1 if this thread is the main thread of its state.
将由 L
表示的线程推入栈。如果此线程是其状态的主线程,则返回 1。
lua_pushvalue
[-0, +1, –]
void lua_pushvalue (lua_State *L, int index);
Pushes a copy of the element at the given index onto the stack.
将给定索引处的元素的副本推入栈。
lua_pushvfstring
[-0, +1, v]
const char *lua_pushvfstring (lua_State *L,
const char *fmt,
va_list argp);
Equivalent to lua_pushfstring
, except that it receives a va_list
instead of a variable number of arguments.
等同于 lua_pushfstring
,除了它接收 va_list
而不是可变数量的参数。
lua_rawequal
[-0, +0, –]
int lua_rawequal (lua_State *L, int index1, int index2);
Returns 1 if the two values in indices index1
and index2
are primitively equal (that is, equal without calling the __eq
metamethod). Otherwise returns 0. Also returns 0 if any of the indices are not valid.
如果索引 index1
和 index2
中的两个值原始相等(即,相等而不调用 __eq
元方法),则返回 1。否则返回 0。如果任何索引无效,也返回 0。
lua_rawget
[-1, +1, –]
int lua_rawget (lua_State *L, int index);
Similar to lua_gettable
, but does a raw access (i.e., without metamethods). The value at index
must be a table.
类似于 lua_gettable
,但执行原始访问(即,不使用元方法)。 index
处的值必须是表。
lua_rawgeti
[-0, +1, –]
int lua_rawgeti (lua_State *L, int index, lua_Integer n);
Pushes onto the stack the value t[n]
, where t
is the table at the given index. The access is raw, that is, it does not use the __index
metavalue.
将值 t[n]
压入栈,其中 t
是给定索引处的表。访问是原始的,即它不使用 __index
元值。
Returns the type of the pushed value.
返回压入值的类型。
lua_rawgetp
[-0, +1, –]
int lua_rawgetp (lua_State *L, int index, const void *p);
Pushes onto the stack the value t[k]
, where t
is the table at the given index and k
is the pointer p
represented as a light userdata. The access is raw; that is, it does not use the __index
metavalue.
将值 t[k]
推送到栈上,其中 t
是给定索引处的表, k
是表示为轻量级用户数据的指针 p
。访问是原始的;也就是说,它不使用 __index
元值。
Returns the type of the pushed value.
返回所推入值的类型。
lua_rawlen
[-0, +0, –]
lua_Unsigned lua_rawlen (lua_State *L, int index);
Returns the raw “length” of the value at the given index: for strings, this is the string length; for tables, this is the result of the length operator (’#
’) with no metamethods; for userdata, this is the size of the block of memory allocated for the userdata. For other values, this call returns 0.
返回给定索引处值的原始“长度”:对于字符串,这是字符串长度;对于表,这是长度运算符 (’ #
‘) 的结果,没有元方法;对于用户数据,这是为用户数据分配的内存块的大小。对于其他值,此调用返回 0。
lua_rawset
[-2, +0, m]
void lua_rawset (lua_State *L, int index);
Similar to lua_settable
, but does a raw assignment (i.e., without metamethods). The value at index
must be a table.
类似于 lua_settable
,但执行原始赋值(即,没有元方法)。 index
处的值必须是表。
lua_rawseti
[-1, +0, m]
void lua_rawseti (lua_State *L, int index, lua_Integer i);
Does the equivalent of t[i] = v
, where t
is the table at the given index and v
is the value on the top of the stack.
执行等同于 t[i] = v
的操作,其中 t
是给定索引处的表, v
是栈顶的值。
This function pops the value from the stack. The assignment is raw, that is, it does not use the __newindex
metavalue.
此函数从栈中弹出值。赋值是原始的,即它不使用 __newindex
元值。
lua_rawsetp
[-1, +0, m]
void lua_rawsetp (lua_State *L, int index, const void *p);
Does the equivalent of t[p] = v
, where t
is the table at the given index, p
is encoded as a light userdata, and v
is the value on the top of the stack.
相当于 t[p] = v
,其中 t
是给定索引处的表, p
被编码为轻量级用户数据, v
是栈顶部的值。
This function pops the value from the stack. The assignment is raw, that is, it does not use the __newindex
metavalue.
此函数从栈中弹出值。赋值是原始的,即它不使用 __newindex
元值。
lua_Reader
typedef const char * (*lua_Reader) (lua_State *L,
void *data,
size_t *size);
The reader function used by lua_load
. Every time lua_load
needs another piece of the chunk, it calls the reader, passing along its data
parameter. The reader must return a pointer to a block of memory with a new piece of the chunk and set size
to the block size. The block must exist until the reader function is called again. To signal the end of the chunk, the reader must return NULL
or set size
to zero. The reader function may return pieces of any size greater than zero.
[-0, +0, e]
lua_register
[-0, +0, e] void lua_register (lua_State *L, const char *name, lua_CFunction f); 将 C 函数 设置为全局 的新值。它被定义为宏:
void lua_register (lua_State *L, const char *name, lua_CFunction f);
Sets the C function f
as the new value of global name
. It is defined as a macro:
#define lua_register(L,n,f) \
(lua_pushcfunction(L, f), lua_setglobal(L, n))
lua_remove
[-1, +0, –]
void lua_remove (lua_State *L, int index);
Removes the element at the given valid index, shifting down the elements above this index to fill the gap. This function cannot be called with a pseudo-index, because a pseudo-index is not an actual stack position.
移除给定有效索引处的元素,将该索引以上的元素向下移动以填补空缺。此函数不能用伪索引调用,因为伪索引不是实际的栈位置。
lua_replace
[-1, +0, –]
void lua_replace (lua_State *L, int index);
Moves the top element into the given valid index without shifting any element (therefore replacing the value at that given index), and then pops the top element.
将栈顶元素移动到给定的有效索引处,而不移动任何元素(因此替换该给定索引处的值),然后弹出栈顶元素。
lua_resetthread
[-0, +?, –]
int lua_resetthread (lua_State *L);
This function is deprecated; it is equivalent to lua_closethread
with from
being NULL
.
此函数已弃用;它等同于 lua_closethread
,其中 from
为 NULL
。
lua_resume
[-?, +?, –]
int lua_resume (lua_State *L, lua_State *from, int nargs,
int *nresults);
Starts and resumes a coroutine in the given thread L
.
在给定线程 L
中启动并恢复协程。
To start a coroutine, you push the main function plus any arguments onto the empty stack of the thread. then you call lua_resume
, with nargs
being the number of arguments. This call returns when the coroutine suspends or finishes its execution. When it returns, *nresults
is updated and the top of the stack contains the *nresults
values passed to lua_yield
or returned by the body function. lua_resume
returns LUA_YIELD
if the coroutine yields, LUA_OK
if the coroutine finishes its execution without errors, or an error code in case of errors (see §4.4.1). In case of errors, the error object is on the top of the stack.
要启动协程,您将主函数以及任何参数推送到线程的空栈上。然后,您调用 lua_resume
,其中 nargs
是参数的数量。此调用在协程挂起或完成其执行时返回。返回时, *nresults
会更新,并且栈顶包含传递给 lua_yield
或由主体函数返回的 *nresults
个值。如果协程产生, lua_resume
返回 LUA_YIELD
;如果协程在没有错误的情况下完成执行,则返回 LUA_OK
;如果发生错误,则返回错误代码(请参阅 §4.4.1)。如果发生错误,错误对象位于栈顶。
To resume a coroutine, you remove the *nresults
yielded values from its stack, push the values to be passed as results from yield
, and then call lua_resume
.
要恢复协程,您需要从其栈中移除 *nresults
个已产生的值,将要作为结果传递的值推送到 yield
,然后调用 lua_resume
。
The parameter from
represents the coroutine that is resuming L
. If there is no such coroutine, this parameter can be NULL
.
参数 from
表示正在恢复的协程 L
。如果不存在这样的协程,此参数可以是 NULL
。
lua_rotate
[-0, +0, –]
void lua_rotate (lua_State *L, int idx, int n);
Rotates the stack elements between the valid index idx
and the top of the stack. The elements are rotated n
positions in the direction of the top, for a positive n
, or -n
positions in the direction of the bottom, for a negative n
. The absolute value of n
must not be greater than the size of the slice being rotated. This function cannot be called with a pseudo-index, because a pseudo-index is not an actual stack position.
在有效索引 idx
和栈顶之间旋转栈元素。元素在正 n
的情况下按顶部方向旋转 n
个位置,或在负 n
的情况下按底部方向旋转 -n
个位置。 n
的绝对值不得大于要旋转的切片的大小。此函数不能用伪索引调用,因为伪索引不是实际的栈位置。
lua_setallocf
[-0, +0, –]
void lua_setallocf (lua_State *L, lua_Alloc f, void *ud);
Changes the allocator function of a given state to f
with user data ud
.
将给定状态的分配器函数更改为 f
,并使用用户数据 ud
。
lua_setfield
[-1, +0, e]
void lua_setfield (lua_State *L, int index, const char *k);
Does the equivalent to t[k] = v
, where t
is the value at the given index and v
is the value on the top of the stack.
执行等同于 t[k] = v
的操作,其中 t
是给定索引处的值, v
是栈顶的值。
This function pops the value from the stack. As in Lua, this function may trigger a metamethod for the “newindex” event (see §2.4).
此函数从栈中弹出值。与 Lua 中一样,此函数可能会触发“newindex”事件的元方法(请参阅 §2.4)。
lua_setglobal
[-1, +0, e]
void lua_setglobal (lua_State *L, const char *name);
Pops a value from the stack and sets it as the new value of global name
.
从栈中弹出值并将其设置为全局变量 name
的新值。
lua_seti
[-1, +0, e]
void lua_seti (lua_State *L, int index, lua_Integer n);
Does the equivalent to t[n] = v
, where t
is the value at the given index and v
is the value on the top of the stack.
相当于 t[n] = v
,其中 t
是给定索引处的值, v
是栈顶的值。
This function pops the value from the stack. As in Lua, this function may trigger a metamethod for the “newindex” event (see §2.4).
此函数从栈中弹出值。与 Lua 中一样,此函数可能会触发“newindex”事件的元方法(参见 §2.4)。
lua_setiuservalue
[-1, +0, –]
int lua_setiuservalue (lua_State *L, int index, int n);
Pops a value from the stack and sets it as the new n
-th user value associated to the full userdata at the given index. Returns 0 if the userdata does not have that value.
从栈中弹出值并将其设置为与给定索引处的完整用户数据关联的新 n
-th 用户值。如果用户数据没有该值,则返回 0。
lua_setmetatable
[-1, +0, –]
int lua_setmetatable (lua_State *L, int index);
Pops a table or nil from the stack and sets that value as the new metatable for the value at the given index. (nil means no metatable.)
从栈中弹出表或 nil,并将该值设置为给定索引处的值的新元表。(nil 表示没有元表。)
(For historical reasons, this function returns an int
, which now is always 1.)
(出于历史原因,此函数返回 int
,现在始终为 1。)
lua_settable
[-2, +0, e]
void lua_settable (lua_State *L, int index);
Does the equivalent to t[k] = v
, where t
is the value at the given index, v
is the value on the top of the stack, and k
is the value just below the top.
执行等同于 t[k] = v
的操作,其中 t
是给定索引处的值, v
是栈顶部的值, k
是紧靠栈顶部的值。
This function pops both the key and the value from the stack. As in Lua, this function may trigger a metamethod for the “newindex” event (see §2.4).
此函数从栈中弹出键和值。与 Lua 中一样,此函数可能会触发“newindex”事件的元方法(请参阅 §2.4)。
lua_settop
[-?, +?, e]
void lua_settop (lua_State *L, int index);
Accepts any index, or 0, and sets the stack top to this index. If the new top is greater than the old one, then the new elements are filled with nil. If index
is 0, then all stack elements are removed.
接受任何索引或 0,并将栈顶部设置为该索引。如果新的顶部大于旧的顶部,则新元素将填充为 nil。如果 index
为 0,则删除所有栈元素。
This function can run arbitrary code when removing an index marked as to-be-closed from the stack.
从栈中删除标记为要关闭的索引时,此函数可以运行任意代码。
lua_setwarnf
[-0, +0, –]
void lua_setwarnf (lua_State *L, lua_WarnFunction f, void *ud);
Sets the warning function to be used by Lua to emit warnings (see lua_WarnFunction
). The ud
parameter sets the value ud
passed to the warning function.
设置 Lua 用于发出警告的警告函数(请参阅 lua_WarnFunction
)。 ud
参数设置传递给警告函数的值 ud
。
lua_State
typedef struct lua_State lua_State;
An opaque structure that points to a thread and indirectly (through the thread) to the whole state of a Lua interpreter. The Lua library is fully reentrant: it has no global variables. All information about a state is accessible through this structure.
指向线程的不透明结构,并间接地(通过线程)指向 Lua 解释器的整个状态。Lua 库是完全可重入的:它没有全局变量。有关状态的所有信息都可以通过此结构访问。
A pointer to this structure must be passed as the first argument to every function in the library, except to lua_newstate
, which creates a Lua state from scratch.
必须将指向此结构的指针作为第一个参数传递给库中的每个函数,除了 lua_newstate
之外,它从头开始创建 Lua 状态。
lua_status
[-0, +0, –]
int lua_status (lua_State *L);
Returns the status of the thread L
.
返回线程 L
的状态。
The status can be LUA_OK
for a normal thread, an error code if the thread finished the execution of a lua_resume
with an error, or LUA_YIELD
if the thread is suspended.
状态可以是正常线程的 LUA_OK
、线程在执行 lua_resume
时出错时的错误代码,或线程被挂起时的 LUA_YIELD
。
You can call functions only in threads with status LUA_OK
. You can resume threads with status LUA_OK
(to start a new coroutine) or LUA_YIELD
(to resume a coroutine).
您只能在状态为 LUA_OK
的线程中调用函数。您可以恢复状态为 LUA_OK
(以启动新的协程)或 LUA_YIELD
(以恢复协程)的线程。
lua_stringtonumber
[-0, +1, –]
size_t lua_stringtonumber (lua_State *L, const char *s);
Converts the zero-terminated string s
to a number, pushes that number into the stack, and returns the total size of the string, that is, its length plus one. The conversion can result in an integer or a float, according to the lexical conventions of Lua (see §3.1). The string may have leading and trailing whitespaces and a sign. If the string is not a valid numeral, returns 0 and pushes nothing. (Note that the result can be used as a boolean, true if the conversion succeeds.)
将以零结尾的字符串 s
转换为数字,将该数字压入栈,并返回字符串的总大小,即其长度加一。根据 Lua 的词法惯例(参见 §3.1),转换结果可以是整数或浮点数。字符串可能带有前导和尾随空格以及符号。如果字符串不是有效的数字,则返回 0 且不压入任何内容。(请注意,结果可以用作布尔值,如果转换成功,则为 true。)
lua_toboolean
[-0, +0, –]
int lua_toboolean (lua_State *L, int index);
int lua_toboolean (lua_State *L, int index);
Converts the Lua value at the given index to a C boolean value (0 or 1). Like all tests in Lua, lua_toboolean
returns true for any Lua value different from false and nil; otherwise it returns false. (If you want to accept only actual boolean values, use lua_isboolean
to test the value’s type.)
将给定索引处的 Lua 值转换为 C 布尔值 (0 或 1)。与 Lua 中的所有测试一样, lua_toboolean
对任何不同于 false 和 nil 的 Lua 值返回 true;否则返回 false。(如果您只想接受实际的布尔值,请使用 lua_isboolean
来测试该值类型。)
lua_tocfunction
[-0, +0, –]
lua_CFunction lua_tocfunction (lua_State *L, int index);
Converts a value at the given index to a C function. That value must be a C function; otherwise, returns NULL
.
将给定索引处的值转换为 C 函数。该值必须是 C 函数;否则,返回 NULL
。
lua_toclose
[-0, +0, m]
void lua_toclose (lua_State *L, int index);
Marks the given index in the stack as a to-be-closed slot (see §3.3.8). Like a to-be-closed variable in Lua, the value at that slot in the stack will be closed when it goes out of scope. Here, in the context of a C function, to go out of scope means that the running function returns to Lua, or there is an error, or the slot is removed from the stack through lua_settop
or lua_pop
, or there is a call to lua_closeslot
. A slot marked as to-be-closed should not be removed from the stack by any other function in the API except lua_settop
or lua_pop
, unless previously deactivated by lua_closeslot
.
将栈中给定索引标记为待关闭槽(请参阅 §3.3.8)。与 Lua 中的待关闭变量一样,当栈中该槽的值超出范围时,它将被关闭。在此,在 C 函数的上下文中,超出范围意味着正在运行的函数返回到 Lua,或者出现错误,或者通过 lua_settop
或 lua_pop
从栈中删除了该槽,或者调用了 lua_closeslot
。标记为待关闭的槽不应通过 API 中的任何其他函数从栈中删除,除非 lua_settop
或 lua_pop
除外,除非先前已通过 lua_closeslot
停用。
This function should not be called for an index that is equal to or below an active to-be-closed slot.
此函数不应被调用以获取等于或低于活动待关闭槽的索引。
Note that, both in case of errors and of a regular return, by the time the __close
metamethod runs, the C stack was already unwound, so that any automatic C variable declared in the calling function (e.g., a buffer) will be out of scope.
请注意,无论在错误情况下还是在正常返回情况下,当 __close
元方法运行时,C 栈已经展开,因此在调用函数中声明的任何自动 C 变量(例如,缓冲区)都将超出范围。
lua_tointeger
[-0, +0, –]
lua_Integer lua_tointeger (lua_State *L, int index);
Equivalent to lua_tointegerx
with isnum
equal to NULL
.
等价于 lua_tointegerx
,其中 isnum
等于 NULL
。
lua_tointegerx
[-0, +0, –]
lua_Integer lua_tointegerx (lua_State *L, int index, int *isnum);
Converts the Lua value at the given index to the signed integral type lua_Integer
. The Lua value must be an integer, or a number or string convertible to an integer (see §3.4.3); otherwise, lua_tointegerx
returns 0.
将给定索引处的 Lua 值转换为有符号整数类型 lua_Integer
。Lua 值必须是整数,或可转换为整数的数字或字符串(参见 §3.4.3);否则, lua_tointegerx
返回 0。
If isnum
is not NULL
, its referent is assigned a boolean value that indicates whether the operation succeeded.
如果 isnum
不等于 NULL
,则为其引用分配一个布尔值,以指示操作是否成功。
lua_tolstring
[-0, +0, m]
const char *lua_tolstring (lua_State *L, int index, size_t *len);
Converts the Lua value at the given index to a C string. If len
is not NULL
, it sets *len
with the string length. The Lua value must be a string or a number; otherwise, the function returns NULL
. If the value is a number, then lua_tolstring
also changes the actual value in the stack to a string. (This change confuses lua_next
when lua_tolstring
is applied to keys during a table traversal.)
将给定索引处的 Lua 值转换为 C 字符串。如果 len
不等于 NULL
,则使用字符串长度设置 *len
。Lua 值必须是字符串或数字;否则,该函数返回 NULL
。如果该值是数字,则 lua_tolstring
还将栈中的实际值更改为字符串。(当在表遍历期间将 lua_tolstring
应用于键时,此更改会混淆 lua_next
。)
lua_tolstring
returns a pointer to a string inside the Lua state (see §4.1.3). This string always has a zero (’\0
’) after its last character (as in C), but can contain other zeros in its body.
lua_tolstring
返回 Lua 状态中字符串的指针(参见 §4.1.3)。此字符串在其最后一个字符后始终带有零(’ \0
‘)(如在 C 中),但其主体中可以包含其他零。
lua_tonumber
[-0, +0, –]
lua_Number lua_tonumber (lua_State *L, int index);
Equivalent to lua_tonumberx
with isnum
equal to NULL
.
等价于 lua_tonumberx
,其中 isnum
等于 NULL
。
lua_tonumberx
[-0, +0, –]
lua_Number lua_tonumberx (lua_State *L, int index, int *isnum);
Converts the Lua value at the given index to the C type lua_Number
(see lua_Number
). The Lua value must be a number or a string convertible to a number (see §3.4.3); otherwise, lua_tonumberx
returns 0.
将给定索引处的 Lua 值转换为 C 类型 lua_Number
(参见 lua_Number
)。Lua 值必须是数字或可转换为数字的字符串(参见 §3.4.3);否则, lua_tonumberx
返回 0。
If isnum
is not NULL
, its referent is assigned a boolean value that indicates whether the operation succeeded.
如果 isnum
不是 NULL
,则为其引用分配一个布尔值,该值指示操作是否成功。
lua_topointer
[-0, +0, –]
const void *lua_topointer (lua_State *L, int index);
Converts the value at the given index to a generic C pointer (void*
). The value can be a userdata, a table, a thread, a string, or a function; otherwise, lua_topointer
returns NULL
. Different objects will give different pointers. There is no way to convert the pointer back to its original value.
将给定索引处的值转换为通用 C 指针(void*
)。该值可以是用户数据、表、线程、字符串或函数;否则, lua_topointer
返回 NULL
。不同的对象将给出不同的指针。无法将指针转换回其原始值。
Typically this function is used only for hashing and debug information.
通常,此函数仅用于哈希和调试信息。
lua_tostring
[-0, +0, m]
const char *lua_tostring (lua_State *L, int index);
Equivalent to lua_tolstring
with len
equal to NULL
.
等同于 lua_tolstring
,其中 len
等于 NULL
。
lua_tothread
[-0, +0, –]
lua_State *lua_tothread (lua_State *L, int index);
Converts the value at the given index to a Lua thread (represented as lua_State*
). This value must be a thread; otherwise, the function returns NULL
.
将给定索引处的数值转换为 Lua 线程(表示为 lua_State*
)。此值必须是线程;否则,该函数将返回 NULL
。
lua_touserdata
[-0, +0, –]
void *lua_touserdata (lua_State *L, int index);
If the value at the given index is a full userdata, returns its memory-block address. If the value is a light userdata, returns its value (a pointer). Otherwise, returns NULL
.
如果给定索引处的数值是完整用户数据,则返回其内存块地址。如果该值是轻量级用户数据,则返回其值(指针)。否则,返回 NULL
。
lua_type
[-0, +0, –]
int lua_type (lua_State *L, int index);
Returns the type of the value in the given valid index, or LUA_TNONE
for a non-valid but acceptable index. The types returned by lua_type
are coded by the following constants defined in lua.h
: LUA_TNIL
, LUA_TNUMBER
, LUA_TBOOLEAN
, LUA_TSTRING
, LUA_TTABLE
, LUA_TFUNCTION
, LUA_TUSERDATA
, LUA_TTHREAD
, and LUA_TLIGHTUSERDATA
.
返回给定有效索引中值的类型,或对于无效但可接受的索引返回 LUA_TNONE
。 lua_type
返回的类型由 lua.h
中定义的以下常量编码: LUA_TNIL
、 LUA_TNUMBER
、 LUA_TBOOLEAN
、 LUA_TSTRING
、 LUA_TTABLE
、 LUA_TFUNCTION
、 LUA_TUSERDATA
、 LUA_TTHREAD
和 LUA_TLIGHTUSERDATA
。
lua_typename
[-0, +0, –]
const char *lua_typename (lua_State *L, int tp);
Returns the name of the type encoded by the value tp
, which must be one the values returned by lua_type
.
返回由值 tp
编码的类型的名称,该值必须是 lua_type
返回的值之一。
lua_Unsigned
typedef ... lua_Unsigned;
The unsigned version of lua_Integer
.
lua_Integer
的无符号版本。
lua_upvalueindex
[-0, +0, –]
int lua_upvalueindex (int i);
Returns the pseudo-index that represents the i
-th upvalue of the running function (see §4.2). i
must be in the range [1,256].
返回表示正在运行的函数的第 i
个上值的伪索引(参见 §4.2)。 i
必须在 [1,256] 范围内。
lua_version
[-0, +0, –]
lua_Number lua_version (lua_State *L);
Returns the version number of this core.
返回此核心的版本号。
lua_WarnFunction
typedef void (*lua_WarnFunction) (void *ud, const char *msg, int tocont);
The type of warning functions, called by Lua to emit warnings. The first parameter is an opaque pointer set by lua_setwarnf
. The second parameter is the warning message. The third parameter is a boolean that indicates whether the message is to be continued by the message in the next call.
警告函数的类型,由 Lua 调用以发出警告。第一个参数是由 lua_setwarnf
设置的不透明指针。第二个参数是警告消息。第三个参数是一个布尔值,指示消息是否由下一次调用中的消息继续。
See warn
for more details about warnings.
有关警告的更多详细信息,请参见 warn
。
lua_warning
[-0, +0, –]
void lua_warning (lua_State *L, const char *msg, int tocont);
Emits a warning with the given message. A message in a call with tocont
true should be continued in another call to this function.
发出带有给定消息的警告。在调用中带有 tocont
true 的消息应在对该函数的另一个调用中继续。
See warn
for more details about warnings.
有关警告的更多详细信息,请参见 warn
。
lua_Writer
typedef int (*lua_Writer) (lua_State *L,
const void* p,
size_t sz,
void* ud);
The type of the writer function used by lua_dump
. Every time lua_dump
produces another piece of chunk, it calls the writer, passing along the buffer to be written (p
), its size (sz
), and the ud
parameter supplied to lua_dump
.
lua_dump
使用的编写器函数的类型。每次 lua_dump
生成另一块块时,它都会调用编写器,传递要写入的缓冲区 ( p
)、其大小 ( sz
) 和提供给 lua_dump
的 ud
参数。
The writer returns an error code: 0 means no errors; any other value means an error and stops lua_dump
from calling the writer again.
编写器返回一个错误代码:0 表示没有错误;任何其他值都表示错误,并阻止 lua_dump
再次调用编写器。
lua_xmove
[-?, +?, –]
void lua_xmove (lua_State *from, lua_State *to, int n);
Exchange values between different threads of the same state.
在同一状态的不同线程之间交换值。
This function pops n
values from the stack from
, and pushes them onto the stack to
.
此函数从栈 from
中弹出 n
个值,并将它们推送到栈 to
中。
lua_yield
[-?, +?, v]
int lua_yield (lua_State *L, int nresults);
This function is equivalent to lua_yieldk
, but it has no continuation (see §4.5). Therefore, when the thread resumes, it continues the function that called the function calling lua_yield
. To avoid surprises, this function should be called only in a tail call.
此函数等同于 lua_yieldk
,但它没有延续(参见 §4.5)。因此,当线程恢复时,它继续调用 lua_yield
的函数的函数。为了避免意外,此函数应仅在尾调用中调用。
lua_yieldk
[-?, +?, v]
int lua_yieldk (lua_State *L,
int nresults,
lua_KContext ctx,
lua_KFunction k);
Yields a coroutine (thread).
让协程(线程)产生。
When a C function calls lua_yieldk
, the running coroutine suspends its execution, and the call to lua_resume
that started this coroutine returns. The parameter nresults
is the number of values from the stack that will be passed as results to lua_resume
.
当 C 函数调用 lua_yieldk
时,正在运行的协程暂停执行,并且启动此协程的 lua_resume
调用返回。参数 nresults
是从栈传递给 lua_resume
作为结果的值的数量。
When the coroutine is resumed again, Lua calls the given continuation function k
to continue the execution of the C function that yielded (see §4.5). This continuation function receives the same stack from the previous function, with the n
results removed and replaced by the arguments passed to lua_resume
. Moreover, the continuation function receives the value ctx
that was passed to lua_yieldk
.
当协程再次恢复时,Lua 调用给定的延续函数 k
以继续执行产生结果的 C 函数(请参阅 §4.5)。此延续函数从前一个函数接收相同的栈,其中 n
结果被移除并替换为传递给 lua_resume
的参数。此外,延续函数接收传递给 lua_yieldk
的值 ctx
。
Usually, this function does not return; when the coroutine eventually resumes, it continues executing the continuation function. However, there is one special case, which is when this function is called from inside a line or a count hook (see §4.7). In that case, lua_yieldk
should be called with no continuation (probably in the form of lua_yield
) and no results, and the hook should return immediately after the call. Lua will yield and, when the coroutine resumes again, it will continue the normal execution of the (Lua) function that triggered the hook.
通常,此函数不会返回;当协程最终恢复时,它将继续执行延续函数。但是,有一个特殊情况,即当此函数从行或计数挂钩内部调用时(请参阅 §4.7)。在这种情况下, lua_yieldk
应在没有延续(可能采用 lua_yield
的形式)和没有结果的情况下调用,并且挂钩应在调用后立即返回。Lua 将让步,当协程再次恢复时,它将继续触发挂钩的(Lua)函数的正常执行。
This function can raise an error if it is called from a thread with a pending C call with no continuation function (what is called a C-call boundary), or it is called from a thread that is not running inside a resume (typically the main thread).
如果此函数是从具有挂起 C 调用且没有延续函数的线程(称为 C 调用边界)中调用,或者是从不在恢复内部运行的线程(通常是主线程)中调用,则此函数可能会引发错误。
4.7 – The Debug Interface 调试接口
Lua has no built-in debugging facilities. Instead, it offers a special interface by means of functions and hooks. This interface allows the construction of different kinds of debuggers, profilers, and other tools that need “inside information” from the interpreter.
Lua 没有内置的调试工具。相反,它通过函数和挂钩提供了一个特殊接口。此接口允许构建不同种类的调试器、分析器和其他需要解释器“内部信息”的工具。
lua_Debug
typedef struct lua_Debug {
int event;
const char *name; /* (n) */
const char *namewhat; /* (n) */
const char *what; /* (S) */
const char *source; /* (S) */
size_t srclen; /* (S) */
int currentline; /* (l) */
int linedefined; /* (S) */
int lastlinedefined; /* (S) */
unsigned char nups; /* (u) number of upvalues */
unsigned char nparams; /* (u) number of parameters */
char isvararg; /* (u) */
char istailcall; /* (t) */
unsigned short ftransfer; /* (r) index of first value transferred */
unsigned short ntransfer; /* (r) number of transferred values */
char short_src[LUA_IDSIZE]; /* (S) */
/* private part */
other fields
} lua_Debug;
A structure used to carry different pieces of information about a function or an activation record. lua_getstack
fills only the private part of this structure, for later use. To fill the other fields of lua_Debug
with useful information, you must call lua_getinfo
with an appropriate parameter. (Specifically, to get a field, you must add the letter between parentheses in the field’s comment to the parameter what
of lua_getinfo
.)
用于携带有关函数或激活记录的不同信息信息结构。 lua_getstack
仅填充此结构的私有部分,以便以后使用。要使用有用的信息填充 lua_Debug
的其他字段,必须使用适当的参数调用 lua_getinfo
。(具体来说,要获取字段,必须将字段注释中的括号内的字母添加到 what
的参数 lua_getinfo
中。)
The fields of lua_Debug
have the following meaning:
lua_Debug
的字段具有以下含义:
source
: the source of the chunk that created the function. Ifsource
starts with a ‘@
’, it means that the function was defined in a file where the file name follows the ‘@
’. Ifsource
starts with a ‘=
’, the remainder of its contents describes the source in a user-dependent manner. Otherwise, the function was defined in a string wheresource
is that string.source
:创建函数的块的源。如果source
以“@
”开头,则表示该函数是在文件名后跟“@
”的文件中定义的。如果source
以“=
”开头,则其内容的其余部分以用户相关的方式描述源。否则,该函数是在字符串中定义的,其中source
是该字符串。srclen
: The length of the stringsource
.srclen
:字符串source
的长度。short_src
: a “printable” version ofsource
, to be used in error messages.short_src
:source
的“可打印”版本,用于错误消息。linedefined
: the line number where the definition of the function starts.linedefined
:函数定义开始的行号。lastlinedefined
: the line number where the definition of the function ends.lastlinedefined
:函数定义结束的行号。what
: the string"Lua"
if the function is a Lua function,"C"
if it is a C function,"main"
if it is the main part of a chunk.what
:字符串"Lua"
(如果函数是 Lua 函数)、"C"
(如果它是 C 函数)、"main"
(如果它是块的主要部分)。currentline
: the current line where the given function is executing. When no line information is available,currentline
is set to -1.currentline
:给定函数正在执行的当前行。当没有行信息可用时,currentline
设置为 -1。name
: a reasonable name for the given function. Because functions in Lua are first-class values, they do not have a fixed name: some functions can be the value of multiple global variables, while others can be stored only in a table field. Thelua_getinfo
function checks how the function was called to find a suitable name. If it cannot find a name, thenname
is set toNULL
.name
:给定函数的合理名称。由于 Lua 中的函数是一等值,因此它们没有固定名称:某些函数可以是多个全局变量的值,而另一些函数只能存储在表字段中。lua_getinfo
函数检查函数的调用方式以查找合适的名称。如果找不到名称,则将name
设置为NULL
。namewhat
: explains thename
field. The value ofnamewhat
can be"global"
,"local"
,"method"
,"field"
,"upvalue"
, or""
(the empty string), according to how the function was called. (Lua uses the empty string when no other option seems to apply.)namewhat
:解释name
字段。根据函数的调用方式,namewhat
的值可以是"global"
、"local"
、"method"
、"field"
、"upvalue"
或""
(空字符串)。(当没有其他选项适用时,Lua 使用空字符串。)istailcall
: true if this function invocation was called by a tail call. In this case, the caller of this level is not in the stack.istailcall
:如果此函数调用是由尾调用调用的,则为 true。在这种情况下,此级别的调用者不在栈中。nups
: the number of upvalues of the function.nups
:函数的上值数。nparams
: the number of parameters of the function (always 0 for C functions).nparams
:函数的参数数(对于 C 函数始终为 0)。isvararg
: true if the function is a variadic function (always true for C functions).isvararg
:如果函数是可变参数函数,则为 true(对于 C 函数始终为 true)。ftransfer
: the index in the stack of the first value being “transferred”, that is, parameters in a call or return values in a return. (The other values are in consecutive indices.) Using this index, you can access and modify these values throughlua_getlocal
andlua_setlocal
. This field is only meaningful during a call hook, denoting the first parameter, or a return hook, denoting the first value being returned. (For call hooks, this value is always 1.)ftransfer
:第一个被“传递”的值在栈中的索引,即调用中的参数或返回中的返回值。(其他值在连续的索引中。)使用此索引,您可以通过lua_getlocal
和lua_setlocal
访问和修改这些值。此字段仅在调用挂钩(表示第一个参数)或返回挂钩(表示第一个被返回的值)期间才有意义。(对于调用挂钩,此值始终为 1。)ntransfer
: The number of values being transferred (see previous item). (For calls of Lua functions, this value is always equal tonparams
.)ntransfer
:正在传递的值的数量(参见上一项)。(对于 Lua 函数的调用,此值始终等于nparams
。)
lua_gethook
[-0, +0, –]
lua_Hook lua_gethook (lua_State *L);
Returns the current hook function.
返回当前挂钩函数。
lua_gethookcount
[-0, +0, –]
int lua_gethookcount (lua_State *L);
Returns the current hook count.
返回当前挂钩计数。
lua_gethookmask
[-0, +0, –]
int lua_gethookmask (lua_State *L);
Returns the current hook mask.
返回当前挂钩掩码。
lua_getinfo
[-(0|1), +(0|1|2), m]
int lua_getinfo (lua_State *L, const char *what, lua_Debug *ar);
Gets information about a specific function or function invocation.
获取有关特定函数或函数调用的信息。
To get information about a function invocation, the parameter ar
must be a valid activation record that was filled by a previous call to lua_getstack
or given as argument to a hook (see lua_Hook
).
要获取有关函数调用的信息,参数 ar
必须是有效的激活记录,该记录由对 lua_getstack
的先前调用填充或作为参数提供给挂钩(请参阅 lua_Hook
)。
To get information about a function, you push it onto the stack and start the what
string with the character ‘>
’. (In that case, lua_getinfo
pops the function from the top of the stack.) For instance, to know in which line a function f
was defined, you can write the following code:
要获取有关函数的信息,请将其推送到栈上,并以字符“ >
”开头 what
字符串。(在这种情况下, lua_getinfo
从栈顶部弹出函数。)例如,要了解函数 f
在哪一行定义,可以编写以下代码:
lua_Debug ar;
lua_getglobal(L, "f"); /* get global 'f' */
lua_getinfo(L, ">S", &ar);
printf("%d\n", ar.linedefined);
Each character in the string what
selects some fields of the structure ar
to be filled or a value to be pushed on the stack. (These characters are also documented in the declaration of the structure lua_Debug
, between parentheses in the comments following each field.)
字符串 what
中的每个字符选择结构 ar
的某些字段以填充或将值压入栈。(这些字符也在结构 lua_Debug
的声明中记录,在每个字段后面的注释中的括号中。)
- ’
f
’: pushes onto the stack the function that is running at the given level; ’f
‘: 将在给定级别运行的函数推入栈; - ’
l
’: fills in the fieldcurrentline
; ’l
‘: 填充字段currentline
; - ’
n
’: fills in the fieldsname
andnamewhat
; ’n
‘: 填充字段name
和namewhat
; - ’
r
’: fills in the fieldsftransfer
andntransfer
; ’r
‘: 填充字段ftransfer
和ntransfer
; - ’
S
’: fills in the fieldssource
,short_src
,linedefined
,lastlinedefined
, andwhat
; ’S
‘: 填写字段source
、short_src
、linedefined
、lastlinedefined
和what
; - ’
t
’: fills in the fieldistailcall
; - ’
t
‘: 填充字段istailcall
; - ’
u
’: fills in the fieldsnups
,nparams
, andisvararg
; - ’
u
‘: 填充字段nups
、nparams
和isvararg
; - ’
L
’: pushes onto the stack a table whose indices are the lines on the function with some associated code, that is, the lines where you can put a break point. (Lines with no code include empty lines and comments.) If this option is given together with option ‘f
’, its table is pushed after the function. This is the only option that can raise a memory error. - ’
L
‘: 将一个表推入栈,其索引是函数中具有某些关联代码的行,即可以放置断点的行。(没有代码的行包括空行和注释。)如果此选项与选项 ’f
’ 一起给出,则其表在函数之后被推入。这是唯一可能引发内存错误的选项。
This function returns 0 to signal an invalid option in what
; even then the valid options are handled correctly.
此函数返回 0 以指示 what
中的无效选项;即使如此,也会正确处理有效选项。
lua_getlocal
[-0, +(0|1), –]
const char *lua_getlocal (lua_State *L, const lua_Debug *ar, int n);
Gets information about a local variable or a temporary value of a given activation record or a given function.
获取给定激活记录或给定函数的局部变量或临时值的信息。
In the first case, the parameter ar
must be a valid activation record that was filled by a previous call to lua_getstack
or given as argument to a hook (see lua_Hook
). The index n
selects which local variable to inspect; see debug.getlocal
for details about variable indices and names.
在第一种情况下,参数 ar
必须是有效的激活记录,该记录由对 lua_getstack
的先前调用填充或作为参数提供给挂钩(请参阅 lua_Hook
)。索引 n
选择要检查的局部变量;有关变量索引和名称的详细信息,请参阅 debug.getlocal
。
lua_getlocal
pushes the variable’s value onto the stack and returns its name.
lua_getlocal
将变量的值推入栈并返回其名称。
In the second case, ar
must be NULL
and the function to be inspected must be on the top of the stack. In this case, only parameters of Lua functions are visible (as there is no information about what variables are active) and no values are pushed onto the stack.
在第二种情况下, ar
必须是 NULL
,并且要检查的函数必须位于栈的顶部。在这种情况下,只有 Lua 函数的参数可见(因为没有关于哪些变量处于活动状态的信息),并且不会将值推送到栈。
Returns NULL
(and pushes nothing) when the index is greater than the number of active local variables.
当索引大于活动局部变量的数量时,返回 NULL
(并且不推送任何内容)。
lua_getstack
[-0, +0, –]
int lua_getstack (lua_State *L, int level, lua_Debug *ar);
Gets information about the interpreter runtime stack.
获取有关解释器运行时栈的信息。
This function fills parts of a lua_Debug
structure with an identification of the activation record of the function executing at a given level. Level 0 is the current running function, whereas level n+1 is the function that has called level n (except for tail calls, which do not count in the stack). When called with a level greater than the stack depth, lua_getstack
returns 0; otherwise it returns 1.
此函数使用给定级别上正在执行的函数的激活记录的标识符填充 lua_Debug
结构的各个部分。级别 0 是当前正在运行的函数,而级别 n+1 是已调用级别 n 的函数(尾调用除外,尾调用不在栈中计数)。当使用大于栈深度的级别调用时, lua_getstack
返回 0;否则,它返回 1。
lua_getupvalue
[-0, +(0|1), –]
const char *lua_getupvalue (lua_State *L, int funcindex, int n);
Gets information about the n
-th upvalue of the closure at index funcindex
. It pushes the upvalue’s value onto the stack and returns its name. Returns NULL
(and pushes nothing) when the index n
is greater than the number of upvalues.
获取闭包在索引 funcindex
处的第 n
个上值的信息。它将上值推入栈并返回其名称。当索引 n
大于上值的数量时,返回 NULL
(并且不推送任何内容)。
See debug.getupvalue
for more information about upvalues.
有关上值的更多信息,请参见 debug.getupvalue
。
lua_Hook
typedef void (*lua_Hook) (lua_State *L, lua_Debug *ar);
Type for debugging hook functions.
用于调试钩子函数的类型。
Whenever a hook is called, its ar
argument has its field event
set to the specific event that triggered the hook. Lua identifies these events with the following constants: LUA_HOOKCALL
, LUA_HOOKRET
, LUA_HOOKTAILCALL
, LUA_HOOKLINE
, and LUA_HOOKCOUNT
. Moreover, for line events, the field currentline
is also set. To get the value of any other field in ar
, the hook must call lua_getinfo
.
每当调用钩子时,其 ar
参数的 event
字段都会设置为触发钩子的特定事件。Lua 使用以下常量标识这些事件: LUA_HOOKCALL
、 LUA_HOOKRET
、 LUA_HOOKTAILCALL
、 LUA_HOOKLINE
和 LUA_HOOKCOUNT
。此外,对于行事件,还会设置字段 currentline
。要获取 ar
中任何其他字段的值,钩子必须调用 lua_getinfo
。
For call events, event
can be LUA_HOOKCALL
, the normal value, or LUA_HOOKTAILCALL
, for a tail call; in this case, there will be no corresponding return event.
对于调用事件, event
可以是 LUA_HOOKCALL
(正常值)或 LUA_HOOKTAILCALL
(尾调用);在这种情况下,不会有相应的返回事件。
While Lua is running a hook, it disables other calls to hooks. Therefore, if a hook calls back Lua to execute a function or a chunk, this execution occurs without any calls to hooks.
当 Lua 正在运行钩子时,它会禁用对钩子的其他调用。因此,如果钩子回调 Lua 来执行函数或块,则此执行将不会调用任何钩子。
Hook functions cannot have continuations, that is, they cannot call lua_yieldk
, lua_pcallk
, or lua_callk
with a non-null k
.
Hook 函数不能有延续,即它们不能使用非空 k
调用 lua_yieldk
、 lua_pcallk
或 lua_callk
。
Hook functions can yield under the following conditions: Only count and line events can yield; to yield, a hook function must finish its execution calling lua_yield
with nresults
equal to zero (that is, with no values).
Hook 函数可以在以下条件下产生:只有计数和行事件才能产生;要产生,hook 函数必须完成其执行,并使用等于零的 nresults
调用 lua_yield
(即没有值)。
lua_sethook
[-0, +0, –]
void lua_sethook (lua_State *L, lua_Hook f, int mask, int count);
Sets the debugging hook function.
设置调试钩子函数。
Argument f
is the hook function. mask
specifies on which events the hook will be called: it is formed by a bitwise OR of the constants LUA_MASKCALL
, LUA_MASKRET
, LUA_MASKLINE
, and LUA_MASKCOUNT
. The count
argument is only meaningful when the mask includes LUA_MASKCOUNT
. For each event, the hook is called as explained below:
参数 f
是钩子函数。 mask
指定钩子将被调用的事件:它由常量 LUA_MASKCALL
、 LUA_MASKRET
、 LUA_MASKLINE
和 LUA_MASKCOUNT
的按位 OR 运算组成。仅当掩码包含 LUA_MASKCOUNT
时, count
参数才有意义。对于每个事件,钩子按如下所述被调用:
- The call hook: is called when the interpreter calls a function. The hook is called just after Lua enters the new function. 调用钩子:在解释器调用函数时被调用。钩子在 Lua 进入新函数后立即被调用。
- The return hook: is called when the interpreter returns from a function. The hook is called just before Lua leaves the function. 返回钩子:在解释器从函数返回时被调用。钩子在 Lua 离开函数之前立即被调用。
- The line hook: is called when the interpreter is about to start the execution of a new line of code, or when it jumps back in the code (even to the same line). This event only happens while Lua is executing a Lua function. 行钩子:在解释器准备开始执行新代码行时,或在代码中跳回时(即使是同一行)被调用。此事件仅在 Lua 执行 Lua 函数时发生。
- The count hook: is called after the interpreter executes every
count
instructions. This event only happens while Lua is executing a Lua function. 计数钩子:在解释器执行每count
条指令后被调用。此事件仅在 Lua 执行 Lua 函数时发生。
Hooks are disabled by setting mask
to zero.
通过将 mask
设置为零来禁用钩子。
lua_setlocal
[-(0|1), +0, –]
const char *lua_setlocal (lua_State *L, const lua_Debug *ar, int n);
Sets the value of a local variable of a given activation record. It assigns the value on the top of the stack to the variable and returns its name. It also pops the value from the stack.
设置给定激活记录的局部变量的值。它将栈顶的值分配给变量并返回其名称。它还会从栈中弹出该值。
Returns NULL
(and pops nothing) when the index is greater than the number of active local variables.
当索引大于活动局部变量的数量时,返回 NULL
(并且不弹出任何内容)。
Parameters ar
and n
are as in the function lua_getlocal
.
参数 ar
和 n
与函数 lua_getlocal
中的参数相同。
lua_setupvalue
[-(0|1), +0, –]
const char *lua_setupvalue (lua_State *L, int funcindex, int n);
Sets the value of a closure’s upvalue. It assigns the value on the top of the stack to the upvalue and returns its name. It also pops the value from the stack.
设置闭包的上值。它将栈顶的值分配给上值并返回其名称。它还会从栈中弹出该值。
Returns NULL
(and pops nothing) when the index n
is greater than the number of upvalues.
当索引 n
大于上值的数量时,返回 NULL
(并且不弹出任何内容)。
Parameters funcindex
and n
are as in the function lua_getupvalue
.
参数 funcindex
和 n
与函数 lua_getupvalue
中的参数相同。
lua_upvalueid
[-0, +0, –]
void *lua_upvalueid (lua_State *L, int funcindex, int n);
Returns a unique identifier for the upvalue numbered n
from the closure at index funcindex
.
返回闭包中编号为 n
的上值的唯一标识符,闭包索引为 funcindex
。
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。
Parameters funcindex
and n
are as in the function lua_getupvalue
, but n
cannot be greater than the number of upvalues.
参数 funcindex
和 n
与函数 lua_getupvalue
中的参数相同,但 n
不能大于上值的数量。
lua_upvaluejoin
[-0, +0, –]
void lua_upvaluejoin (lua_State *L, int funcindex1, int n1,
int funcindex2, int n2);void lua_upvaluejoin (lua_State *L, int funcindex1, int n1,
int funcindex2, int n2);
Make the n1
-th upvalue of the Lua closure at index funcindex1
refer to the n2
-th upvalue of the Lua closure at index funcindex2
.
使索引为 funcindex1
的 Lua 闭包的第 n1
个上值引用索引为 funcindex2
的 Lua 闭包的第 n2
个上值。