Lua Lua 5.5 参考手册

作者:Roberto Ierusalimschy、Luiz Henrique de Figueiredo、Waldemar Celes

版权 © 2020–2026 Lua.org, PUC-Rio。 依据 Lua 许可证 的条款自由使用。

1 – 简介

Lua 是一门强大、高效、轻量、可嵌入的脚本语言。 它支持过程式编程、面向对象编程、函数式编程、数据驱动编程以及数据描述。

Lua 将简单的过程式语法与基于关联数组、语义可扩展的强大数据描述构造结合在一起。 Lua 是动态类型语言,通过解释字节码、运行在基于寄存器的虚拟机上, 并具备自动内存管理(采用分代垃圾回收), 因而非常适于配置、脚本编写以及快速原型开发。

Lua 以库的形式实现,用 纯 C(标准 C 与 C++ 的公共子集)编写。 Lua 发行版包含一个名为 lua 的主机程序, 它借助 Lua 库提供一个完整、独立的 Lua 解释器, 可用于交互式或批处理用途。 Lua 既可作为任意需要脚本功能的程序所用的、强大而轻量的可嵌入脚本语言, 也可作为强大却轻量高效、独立运行的编程语言。

作为一种扩展语言,Lua 没有“主程序”的概念: 它 嵌入 在一个称为 嵌入程序(或简称 宿主)的主机客户端中运行。 (通常这个宿主就是独立的 lua 程序。) 宿主程序可以调用函数来执行一段 Lua 代码, 可以读写 Lua 变量, 也可以注册供 Lua 代码调用的 C 函数。 借助 C 函数,Lua 可被增强以胜任众多不同的领域, 从而构建出共享同一语法框架的、定制化的编程语言。

Lua 是自由软件, 按照其许可证的声明,照例不提供任何担保。 本手册所描述的实现可在 Lua 官方网站 www.lua.org 获取。

与任何其它参考手册一样,本文档在某些地方略显枯燥。 关于 Lua 设计背后决策的讨论,请参阅 Lua 网站上的技术论文。 关于 Lua 编程的详尽入门,请参阅 Roberto 的著作 《Programming in Lua》

2 – 基本概念

本节描述该语言的基本概念。

2.1 – 值与类型

Lua is a dynamically typed language. This means that variables do not have types; only values do. There are no type definitions in the language. All values carry their own type.

Lua 中的所有值都是一等值(first-class values)。 这意味着所有值都可以存入变量、 作为实参传给其它函数,并作为结果返回。

Lua 中有八种基本类型: nil(空)、boolean(布尔)、number(数字)、 string(字符串)、function(函数)、userdata(用户数据)、 thread(线程)和 table(表)。 类型 nil 只有一个值 nil, 其主要特性是不同于任何其它值; 它通常表示“没有有用的值”。 类型 boolean 有两个值:falsetruenilfalse 都会使条件为假; 它们被统称为 假值(false values)。 任何其它值都使条件为真。 尽管名字如此,false 常被用作 nil 的替代, 关键区别在于:false 在表中表现得像一个普通值, 而表中的 nil 表示一个缺失的键。

类型 number 表示整数与实数(浮点数), 使用两个子类型:integer(整数)和 float(浮点数)。 标准 Lua 使用 64 位整数和双精度(64 位)浮点数, 但你也可以编译 Lua,使其使用 32 位整数和/或单精度(32 位)浮点数。 整数与浮点数都为 32 位的选项 对于小型机器和嵌入式系统尤其有吸引力。 (参见文件 luaconf.h 中的宏 LUA_32BITS。)

除非另有说明, 对整数值进行运算时,若发生溢出则按 环绕(wrap around) 处理, 遵循补码运算的通常规则。 (换言之,实际结果是唯一可表示的整数, 在模 2n 意义下与数学结果相等, 其中 n 是该整数类型的位数。)

Lua 对每种子类型的使用时机有明确规则, 但也会在需要时自动在二者之间转换(见 §3.4.3)。 因此,程序员可以选择基本忽略整数与浮点数之间的差异, 也可以完全掌控每个数字的表示方式。

类型 string 表示不可变的字节序列。 Lua 是 8 位干净的: 字符串可以包含任意 8 位值, 包括内嵌的零('\0')。 Lua 也是编码无关的; 它不对字符串的内容做任何假设。 Lua 中任意字符串的长度必须能存入一个 Lua 整数, 且字符串加上一个小头部必须能放入 size_t

Lua 可以调用(并操作)用 Lua 编写的函数, 以及用 C 编写的函数(见 §3.4.10)。 二者都由类型 function 表示。

类型 userdata 用于允许将任意 C 数据 存入 Lua 变量。 一个 userdata 值表示一块原始内存。 userdata 有两种: full userdata(完整用户数据), 即由 Lua 管理一块内存的对象; 以及 light userdata(轻量用户数据), 即一个简单的 C 指针值。 在 Lua 中,userdata 没有预定义的操作, 除了赋值与一致性测试。 通过使用 元表(metatables), 程序员可以为完整 userdata 值定义操作 (见 §2.4)。 userdata 值不能在 Lua 中创建或修改, 只能通过 C API 进行。 这保证了宿主程序和 C 库所拥有数据的完整性。

类型 thread 表示独立的执行线程, 用于实现协程(coroutines,见 §2.6)。 Lua 的线程与操作系统线程无关。 Lua 在所有系统上都支持协程, 即便是那些原生不支持线程的系统。

类型 table 实现的是关联数组, 即不仅可以用数字作索引, 还可以用除 nil 和 NaN 之外的任意 Lua 值作索引的数组。 (NaN(Not a Number) 是 IEEE 754 标准用来 表示未定义数值结果(如 0/0)的特殊浮点值。) 表可以是 异构(heterogeneous) 的; 也就是说,它可以包含所有类型的值(nil 除外)。 任何与值 nil 关联的键都不被视为表的一部分。 反之,任何不属于表的键,其关联值都是 nil

表是 Lua 中唯一的数据结构机制; 它可以用来表示普通数组、列表、符号表、集合、记录、图、树等等。 为表示记录,Lua 用字段名作为索引。 语言通过提供 a.name 作为 a["name"] 的语法糖来支持这种表示法。 Lua 中有几种方便的建表方式(见 §3.4.9)。

与索引一样, 表字段的值可以是任意类型。 特别地,因为函数是一等值, 表字段可以包含函数。 因此表也可以携带 方法(methods)(见 §3.4.11)。

表的索引遵循语言中“原始相等(raw equality)”的定义。 表达式 a[i]a[j] 表示同一个表元素, 当且仅当 ij 原始相等 (即不使用元方法时的相等)。 特别地,具有整数值的浮点数 等于其对应的整数 (例如 1.0 == 1)。 为避免歧义,任何用作键、且等于某整数的浮点数 都会被转换为该整数。 例如,若你写 a[2.0] = true, 实际插入表中的键将是整数 2

表、函数、线程和(完整)userdata 值都是 对象(objects): 变量并不真正 包含 这些值, 只持有对它们的 引用(references)。 赋值、参数传递和函数返回 操作的始终是对这些值的引用; 这些操作不涉及任何复制。

库函数 type 返回一个描述给定值类型的字符串 (见 type)。

2.2 – 作用域、变量与环境

变量名所指的是全局变量还是局部变量, 取决于代码该处上下文中生效的声明。 (就本讨论而言,函数的形式参数等同于局部变量。)

所有代码块(chunk)都以一个隐式声明 global * 开始, 它将所有自由名声明为全局变量; 正如下面的例子所示,这一前缀声明在任何其它 global 声明的作用域内失效:

     X = 1       -- Ok, global by default
     do
       global Y  -- voids the implicit initial declaration
       Y = 1     -- Ok, Y declared as global
       X = 1     -- ERROR, X not declared
     end
     X = 2       -- Ok, global by default again

因此,在任何 global 声明之外, Lua 表现为“默认全局”。 在任何 global 声明之内, Lua 没有默认行为:所有变量都必须声明。

Lua 是一门词法作用域(lexically scoped)语言。 变量声明的作用域从声明之后的第一条语句开始, 一直延续到包含该声明的最内层块的最后一条非空语句。 (空语句(void statements) 指标签和空语句。)

声明会遮蔽(shadow)在该声明处上下文中同名的任何声明。 在这个遮蔽范围内,该名称的任何外层声明都失效。 见下例:

     global print, x
     x = 10                -- global variable
     do                    -- new block
       local x = x         -- new 'x', with value 10
       print(x)            --> 10
       x = x+1
       do                  -- another block
         local x = x+1     -- another 'x'
         print(x)          --> 12
       end
       print(x)            --> 11
     end
     print(x)              --> 10  (the global one)

注意,在像 local x = x 这样的声明中, 正在声明的新 x 尚未进入作用域, 因此右侧的 x 指的是外层变量。

由于词法作用域规则, 内部定义的函数可以自由访问其作用域内的局部变量。 被内层函数使用的局部变量,在内层函数中称为 upvalue (或 外部局部变量,或简称 外部变量)。

注意,每次执行 local 语句都会定义新的局部变量。 考虑下例:

     a = {}
     local x = 20
     for i = 1, 10 do
       local y = 0
       a[i] = function () y = y + 1; return x + y end
     end

该循环创建了十个闭包 (即该匿名函数的十个实例)。 这些闭包各自使用不同的 y 变量, 但它们共享同一个 x

正如我们将在 §3.2§3.3.3 进一步讨论的, 对任何全局变量 var 的引用 在语法上都会被翻译为 _ENV.var。 此外,每个代码块都在一个名为 _ENV 的外部局部变量的作用域内编译 (见 §3.3.2), 因此 _ENV 本身永远不会是代码块中的自由名。

尽管存在这个外部 _ENV 变量以及对自由名的翻译, _ENV 仍然是一个普通名字。 特别地,你可以用这个名字定义新的变量和参数。 (不过,你不应把 _ENV 定义为全局变量, 否则 _ENV.var 会被翻译成 _ENV._ENV.var,如此循环往复,陷入无限循环。) 每次对全局变量名的引用,都使用程序中该处可见的 _ENV

任何用作 _ENV 值的表都称为一个 环境(environment)

Lua 维护一个特殊的、称为 全局环境(global environment) 的环境。 该值保存在 C 注册表(registry,见 §4.3)的一个特殊索引处。 在 Lua 中,全局变量 _G 被初始化为同一个值。 (_G 在内部从不被使用, 因此改变其值只会影响你自己的代码。)

当 Lua 加载一个代码块时, 其 _ENV 变量的默认值是全局环境(见 load)。 因此,默认情况下, Lua 代码中的全局变量指向全局环境中的条目, 从而表现得像传统的全局变量。 此外,所有标准库都被加载到全局环境中, 其中一些函数会操作该环境。 你可以使用 load(或 loadfile) 以一个不同的环境加载代码块。 (在 C 中,你必须先加载代码块,再修改其第一个 upvalue; 见 lua_setupvalue。)

2.3 – 错误处理

Several operations in Lua can raise an error. An error interrupts the normal flow of the program, which can continue by catching the error.

Lua code can explicitly raise an error by calling the error function. (This function never returns.)

To catch errors in Lua, you can do a protected call, using pcall (or xpcall). The function pcall calls a given function in protected mode. Any error while running the function stops its execution, and control returns immediately to pcall, which returns a status code.

Because Lua is an embedded extension language, Lua code starts running by a call from C code in the host program. (When you use Lua standalone, the lua application is the host program.) Usually, this call is protected; so, when an otherwise unprotected error occurs during the compilation or execution of a Lua chunk, control returns to the host, which can take appropriate measures, such as printing an error message.

Whenever there is an error, an error object is propagated with information about the error. Lua itself only generates errors whose error object is a string, but programs can generate errors with any value as the error object, except nil. (Lua will change a nil as error object to a string message.) It is up to the Lua program or its host to handle such error objects. For historical reasons, an error object is often called an error message, even though it does not have to be a string.

When you use xpcall (or lua_pcall, in C) you can give a message handler to be called in case of errors. This function is called with the original error object and returns a new error object. It is called before the error unwinds the stack, so that it can gather more information about the error, for instance by inspecting the stack and creating a stack traceback. This message handler is still protected by the protected call; so, an error inside the message handler will call the message handler again. If this loop goes on for too long, Lua breaks it and returns an appropriate message. The message handler is called only for regular runtime errors. It is not called for memory-allocation errors nor for errors while running finalizers or other message handlers.

Lua also offers a system of warnings (see warn). Unlike errors, warnings do not interfere in any way with program execution. They typically only generate a message to the user, although this behavior can be adapted from C (see lua_setwarnf).

2.4 – 元表与元方法

Every value in Lua can have a metatable. This metatable is an ordinary Lua table that defines the behavior of the original value under certain events. You can change several aspects of the behavior of a value by setting specific fields in its metatable. For instance, when a non-numeric value is the operand of an addition, Lua checks for a function in the field __add of the value's metatable. If it finds one, Lua calls this function to perform the addition.

The key for each event in a metatable is a string with the event name prefixed by two underscores; the corresponding value is called a metavalue. For most events, the metavalue must be a function, which is then called a metamethod. In the previous example, the key is the string "__add" and the metamethod is the function that performs the addition. Unless stated otherwise, a metamethod can in fact be any callable value, which is either a function or a value with a __call metamethod.

You can query the metatable of any value using the getmetatable function. Lua queries metamethods in metatables using a raw access (see rawget).

You can replace the metatable of tables using the setmetatable function. You cannot change the metatable of other types from Lua code, except by using the debug library (§6.11).

Tables and full userdata have individual metatables, although multiple tables and userdata can share their metatables. Values of all other types share one single metatable per type; that is, there is one single metatable for all numbers, one for all strings, etc. By default, a value has no metatable, but the string library sets a metatable for the string type (see §6.5).

A detailed list of operations controlled by metatables is given next. Each event is identified by its corresponding key. By convention, all metatable keys used by Lua are composed by two underscores followed by lowercase Latin letters.

In addition to the previous list, the interpreter also respects the following keys in metatables: __gc (see §2.5.3), __close (see §3.3.8), __mode (see §2.5.4), and __name. (The entry __name, when it contains a string, may be used by tostring and in error messages.)

For the unary operators (negation, length, and bitwise NOT), the metamethod is computed and called with a dummy second operand, equal to the first one. This extra operand is only to simplify Lua's internals (by making these operators behave like a binary operation) and may be removed in future versions. For most uses this extra operand is irrelevant.

Because metatables are regular tables, they can contain arbitrary fields, not only the event names defined above. Some functions in the standard library (e.g., tostring) use other fields in metatables for their own purposes.

It is a good practice to add all needed metamethods to a table before setting it as a metatable of some object. In particular, the __gc metamethod works only when this order is followed (see §2.5.3). It is also a good practice to set the metatable of an object right after its creation.

2.5 – 垃圾回收

Lua performs automatic memory management. This means that you do not have to worry about allocating memory for new objects or freeing it when the objects are no longer needed. Lua manages memory automatically by running a garbage collector to collect all dead objects. All memory used by Lua is subject to automatic management: strings, tables, userdata, functions, threads, internal structures, etc.

An object is considered dead as soon as the collector can be sure the object will not be accessed again in the normal execution of the program. ("Normal execution" here excludes finalizers, which resurrect dead objects (see §2.5.3), and it excludes also some operations using the debug library.) Note that the time when the collector can be sure that an object is dead may not coincide with the programmer's expectations. The only guarantees are that Lua will not collect an object that may still be accessed in the normal execution of the program, and it will eventually collect an object that is inaccessible from Lua. (Here, inaccessible from Lua means that neither a variable nor another live object refer to the object.) Because Lua has no knowledge about C code, it never collects objects accessible through the registry (see §4.3), which includes the global environment (see §2.2) and the main thread.

The garbage collector (GC) in Lua can work in two modes: incremental and generational.

The default GC mode with the default parameters are adequate for most uses. However, programs that waste a large proportion of their time allocating and freeing memory can benefit from other settings. Keep in mind that the GC behavior is non-portable both across platforms and across different Lua releases; therefore, optimal settings are also non-portable.

You can change the GC mode and parameters by calling lua_gc in C or collectgarbage in Lua. You can also use these functions to control the collector directly, for instance to stop or restart it.

2.5.1 – Incremental Garbage Collection

In incremental mode, each GC cycle performs a mark-and-sweep collection in small steps interleaved with the program's execution. In this mode, the collector uses three numbers to control its garbage-collection cycles: the garbage-collector pause, the garbage-collector step multiplier, and the garbage-collector step size.

The garbage-collector pause controls how long the collector waits before starting a new cycle. The collector starts a new cycle when the number of bytes hits n% of the total after the previous collection. Larger values make the collector less aggressive. Values equal to or less than 100 mean the collector will not wait to start a new cycle. A value of 200 means that the collector waits for the total number of bytes to double before starting a new cycle.

The garbage-collector step size controls the size of each incremental step, specifically how many bytes the interpreter allocates before performing a step: A value of n means the interpreter will allocate approximately n bytes between steps.

The garbage-collector step multiplier controls how much work each incremental step does. A value of n means the interpreter will execute n% units of work for each word allocated. A unit of work corresponds roughly to traversing one slot or sweeping one object. Larger values make the collector more aggressive. Beware that values too small can make the collector too slow to ever finish a cycle. As a special case, a zero value means unlimited work, effectively producing a non-incremental, stop-the-world collector.

2.5.2 – Generational Garbage Collection

In generational mode, the collector does frequent minor collections, which traverses only objects recently created. If after a minor collection the number of bytes is above a limit, the collector shifts to a major collection, which traverses all objects. The collector will then stay doing major collections until it detects that the program is generating enough garbage to justify going back to minor collections.

The generational mode uses three parameters: the minor multiplier, the minor-major multiplier, and the major-minor multiplier.

The minor multiplier controls the frequency of minor collections. For a minor multiplier x, a new minor collection will be done when the number of bytes grows x% larger than the number in use just after the last major collection. For instance, for a multiplier of 20, the collector will do a minor collection when the number of bytes gets 20% larger than the total after the last major collection.

The minor-major multiplier controls the shift to major collections. For a multiplier x, the collector will shift to a major collection when the number of bytes from old objects grows x% larger than the total after the previous major collection. For instance, for a multiplier of 100, the collector will do a major collection when the number of old bytes gets larger than twice the total after the previous major collection. As a special case, a value of 0 stops the collector from doing major collections.

The major-minor multiplier controls the shift back to minor collections. For a multiplier x, the collector will shift back to minor collections after a major collection collects at least x% of the bytes allocated during the last cycle. In particular, for a multiplier of 0, the collector will immediately shift back to minor collections after doing one major collection.

2.5.3 – Garbage-Collection Metamethods

You can set garbage-collector metamethods for tables and, using the C API, for full userdata (see §2.4). These metamethods, called finalizers, are called when the garbage collector detects that the corresponding table or userdata is dead. Finalizers allow you to coordinate Lua's garbage collection with external resource management such as closing files, network or database connections, or freeing your own memory.

For an object (table or userdata) to be finalized when collected, you must mark it for finalization. You mark an object for finalization when you set its metatable and the metatable has a __gc metamethod. Note that if you set a metatable without a __gc field and later create that field in the metatable, the object will not be marked for finalization.

When a marked object becomes dead, it is not collected immediately by the garbage collector. Instead, Lua puts it in a list. After the collection, Lua goes through that list. For each object in the list, it checks the object's __gc metamethod: If it is present, Lua calls it with the object as its single argument.

At the end of each garbage-collection cycle, the finalizers are called in the reverse order that the objects were marked for finalization, among those collected in that cycle; that is, the first finalizer to be called is the one associated with the object marked last in the program. The execution of each finalizer may occur at any point during the execution of the regular code.

Because the object being collected must still be used by the finalizer, that object (and other objects accessible only through it) must be resurrected by Lua. Usually, this resurrection is transient, and the object memory is freed in the next garbage-collection cycle. However, if the finalizer stores the object in some global place (e.g., a global variable), then the resurrection is permanent. Moreover, if the finalizer marks a finalizing object for finalization again, its finalizer will be called again in the next cycle where the object is dead. In any case, the object memory is freed only in a GC cycle where the object is dead and not marked for finalization.

When you close a state (see lua_close), Lua calls the finalizers of all objects marked for finalization, following the reverse order that they were marked. If any finalizer marks objects for collection during that phase, these marks have no effect.

Finalizers cannot yield nor run the garbage collector. Because they can run in unpredictable times, it is good practice to restrict each finalizer to the minimum necessary to properly release its associated resource.

Any error while running a finalizer generates a warning; the error is not propagated.

2.5.4 – Weak Tables

A weak table is a table whose elements are weak references. A weak reference is ignored by the garbage collector. In other words, if the only references to an object are weak references, then the garbage collector will collect that object.

A weak table can have weak keys, weak values, or both. A table with weak values allows the collection of its values, but prevents the collection of its keys. A table with both weak keys and weak values allows the collection of both keys and values. In any case, if either the key or the value is collected, the whole pair is removed from the table. The weakness of a table is controlled by the __mode field of its metatable. This metavalue, if present, must be one of the following strings: "k", for a table with weak keys; "v", for a table with weak values; or "kv", for a table with both weak keys and values.

A table with weak keys and strong values is also called an ephemeron table. In an ephemeron table, a value is considered reachable only if its key is reachable. In particular, if the only reference to a key comes through its value, the pair is removed.

Any change in the weakness of a table may take effect only at the next collect cycle. In particular, if you change the weakness to a stronger mode, Lua may still collect some items from that table before the change takes effect.

只有具备显式构造的对象才会从弱表中移除。 数字和轻量 C 函数等值 不受垃圾回收影响, 因此不会从弱表中移除 (除非它们关联的值被回收)。 尽管字符串受垃圾回收管理, 但它们没有显式构造、 且按值相等; 它们表现得更像值而非对象。 因此,它们不会从弱表中移除。

被复活的对象 (即正在被终结的对象, 以及只能通过正在被终结的对象访问到的对象) 在弱表中有特殊行为。 它们会在运行终结器之前从弱值中移除, 但只在运行终结器之后的下一次回收中(当这些对象被真正释放时) 才从弱键中移除。 这一行为允许终结器通过弱表访问 与该对象关联的属性。

如果弱表是某次回收周期中被复活的对象之一, 它可能要到下一个周期才能被正确清理。

2.6 – 协程

Lua 支持协程(coroutines), 也称为 协作式多线程(collaborative multithreading)。 Lua 中的协程表示一条独立的执行线程。 不过,与多线程系统中的线程不同, 协程只有通过显式调用 一个 yield 函数才会挂起其执行。

你通过调用 coroutine.create 创建协程。 它的唯一参数是一个函数, 即协程的主函数。 create 函数只创建一个新协程并返回其句柄 (一个 thread 类型的对象); 它并不启动协程。

你通过调用 coroutine.resume 执行协程。 当你首次调用 coroutine.resume、 并以其第一个参数为 coroutine.create 返回的线程时, 协程会通过调用其主函数开始执行。 传给 coroutine.resume 的额外参数 会作为该函数的参数传入。 协程开始运行后, 会一直执行到终止或 让出(yield)

协程可以通过两种方式终止其执行: 正常方式,即其主函数返回 (显式或隐式,在最后一条指令之后); 以及异常方式,即出现一个未受保护的错误。 正常终止时, coroutine.resume 返回 true, 外加协程主函数返回的任何值。 出错时,coroutine.resume 返回 false 外加错误对象。 这种情况下,协程不会展开其栈, 因此可以在出错后用调试 API 检查它。

协程通过调用 coroutine.yield 让出。 当协程让出时, 对应的 coroutine.resume 会立即返回, 即使让出发生在嵌套函数调用内部 (即不在主函数中, 而在被主函数直接或间接调用的函数中)。 让出的情况下,coroutine.resume 也返回 true, 外加传给 coroutine.yield 的任何值。 下次你再次恢复同一个协程时, 它会从让出处继续执行, 此时对 coroutine.yield 的调用会返回 传给 coroutine.resume 的任何额外参数。

coroutine.create 类似, coroutine.wrap 函数也能创建协程, 但它不返回协程本身, 而是返回一个函数,调用该函数时会恢复协程。 传给这个函数的任何参数 都会作为额外参数传给 coroutine.resumecoroutine.wrap 返回 coroutine.resume 返回的所有值, 但第一个(布尔错误码)除外。 与 coroutine.resume 不同, 由 coroutine.wrap 创建的函数 会把任何错误传播给调用者。 此时,该函数还会关闭协程(见 coroutine.close)。

作为协程如何工作的例子,考虑下面这段代码:

     function foo (a)
       print("foo", a)
       return coroutine.yield(2*a)
     end
     
     co = coroutine.create(function (a,b)
           print("co-body", a, b)
           local r = foo(a+1)
           print("co-body", r)
           local r, s = coroutine.yield(a+b, a-b)
           print("co-body", r, s)
           return b, "end"
     end)
     
     print("main", coroutine.resume(co, 1, 10))
     print("main", coroutine.resume(co, "r"))
     print("main", coroutine.resume(co, "x", "y"))
     print("main", coroutine.resume(co, "x", "y"))

运行它时,会产生如下输出:

     co-body 1       10
     foo     2
     main    true    4
     co-body r
     main    true    11      -9
     co-body x       y
     main    true    10      end
     main    false   cannot resume dead coroutine

你也可以通过 C API 创建和操作协程: 参见函数 lua_newthreadlua_resumelua_yield

3 – 语言

本节描述 Lua 的词法、语法和语义。 换言之, 本节描述哪些记号(token)是合法的、 它们如何组合, 以及这些组合的含义。

语言构造将用通常的扩展 BNF 记号说明, 其中 {a} 表示 0 个或多个 a, [a] 表示可选的 a。 非终结符显示为 non-terminal, 关键字显示为 kword, 其它终结符显示为 ‘=’。 Lua 的完整语法可在本手册末尾的 §9 找到。

3.1 – 词法约定

Lua 是一种自由格式(free-form)语言。 它会忽略词法元素(token)之间的空格与注释, 除非它们充当两个 token 之间的分隔符。 在源代码中, Lua 将标准的 ASCII 空白字符——空格、换页、换行、 回车、水平制表符和垂直制表符——视为空格。

名字(Names) (也称 标识符(identifiers)) 在 Lua 中可以是任意由拉丁字母、 阿拉伯-印度数字和下划线组成的字符串, 但不能以数字开头, 也不能是保留字。 标识符用于命名变量、表字段和标签。

以下 关键字(keywords) 是保留的, 不能用作名字:

     and       break     do        else      elseif    end
     false     for       function  global    goto      if
     in        local     nil       not       or        repeat
     return    then      true      until     while

Lua 是一门大小写敏感的语言: and 是保留字,但 AndAND 是两个不同且合法的名字。 按照惯例, 程序应避免创建以下划线开头、 后接一个或多个大写字母的名字 (如 _VERSION)。

以下字符串表示其它 token:

     +     -     *     /     %     ^     #
     &     ~     |     <<    >>    //
     ==    ~=    <=    >=    <     >     =
     (     )     {     }     [     ]     ::
     ;     :     ,     .     ..    ...

短字符串字面量(short literal string) 可以用配对的单引号或双引号界定, 并可以包含以下类 C 的转义序列: '\a'(响铃)、 '\b'(退格)、 '\f'(换页)、 '\n'(换行)、 '\r'(回车)、 '\t'(水平制表)、 '\v'(垂直制表)、 '\\'(反斜杠)、 '\"'(双引号)、 以及 '\''(单引号)。 反斜杠后紧跟换行会在字符串中产生一个换行。 转义序列 '\z' 会跳过其后的一段 空白字符(包括换行); 它特别适合把一个长字符串字面量拆成多行并缩进, 而不把那些换行和空格加入字符串内容。 短字符串字面量不能包含未转义的换行, 也不能包含不构成有效转义序列的转义。

在短字符串字面量中, 我们可以通过数值指定任意字节, 包括内嵌的零。 这可以通过转义序列 \xXX 实现, 其中 XX 恰好是两个十六进制数字, 或者用转义序列 \ddd, 其中 ddd 是最多三个十进制数字。 (注意:若十进制转义序列后紧跟一个数字, 则它必须用恰好三位数字表示。)

Unicode 字符的 UTF-8 编码 可以通过转义序列 \u{XXX} (必须带花括号)插入到字符串字面量中, 其中 XXX 是一个或多个十六进制数字序列, 表示该字符的码点。 该码点可以是小于 231 的任意值。 (Lua 此处使用原始的 UTF-8 规范, 并未限制为有效的 Unicode 码点。)

字符串字面量也可以用由 长括号(long brackets) 包围的长格式定义。 我们定义 级别为 n 的开长括号 为: 一个开方括号,后跟 n 个等号,再跟另一个开方括号。 因此,级别为 0 的开长括号写作 [[, 级别为 1 的开长括号写作 [=[,依此类推。 闭长括号 类似定义; 例如,级别为 4 的闭长括号写作 ]====]长字面量 以任意级别的开长括号开始, 到第一个同级别的闭长括号结束。 它可以包含除同级闭括号外的任意文本。 这种括号形式的字面量可以跨多行, 不解释任何转义序列, 并忽略任何其它级别的长括号。 任意类型的行尾序列 (回车、换行、回车加换行, 或换行加回车)都会被转换为简单的换行。 当开长括号后紧跟一个换行时, 该换行不会被包含在字符串中。

例如,在使用 ASCII 的系统中 (其中 'a' 编码为 97, 换行编码为 10,'1' 编码为 49), 下面五个字符串字面量表示同一个字符串:

     a = 'alo\n123"'
     a = "alo\n123\""
     a = '\97lo\10\04923"'
     a = [[alo
     123"]]
     a = [==[
     alo
     123"]==]

字符串字面量中, 未被前述规则显式影响的任意字节都表示其自身。 不过,Lua 以文本模式打开文件进行解析, 系统的文件函数可能对某些控制字符有问题。 因此,更安全的做法是: 把二进制数据表示为带引号的字面量, 并对非文本字符使用显式转义序列。

数值常量(numeric constant)(或称 numeral) 可以带可选的小数部分和可选的十进制指数, 指数用字母 'e' 或 'E' 标记。 Lua 也接受十六进制常量, 以 0x0X 开头。 十六进制常量还接受可选的小数部分 加上可选的二进制指数, 二进制指数用字母 'p' 或 'P' 标记,并以十进制书写。 (例如,0x1.fp10 表示 1984, 即 0x1f / 16 乘以 210。)

带小数点或指数的数值常量表示 float; 否则,若其值能放入整数或是十六进制常量, 则它表示整数; 否则(即溢出的十进制整数常量)它表示 float。 既无小数点也无指数的十六进制数字 总表示整数值; 若其值溢出,则 环绕(wraps around) 以适配一个有效的整数。

合法的整型常量示例如下:

     3   345   0xff   0xBEBADA

合法的浮点常量示例如下:

     3.0     3.1416     314.16e-2     0.31416E1     34e1
     0x0.1E  0xA23p-4   0X1.921FB54442D18P+1

注释(comment) 以双连字符(--)开始, 出现在字符串之外的任何位置。 如果 -- 之后的文本不是开长括号, 则该注释为 短注释(short comment), 一直延续到行尾。 否则它是 长注释(long comment), 一直延续到对应的闭长括号。

3.2 – 变量

变量是存储值的位置。 Lua 中有三种变量: 全局变量、局部变量和表字段。

单个名字可以表示一个全局变量或局部变量 (或函数的形式参数, 它是一种特殊的局部变量)(见 §2.2):

	var ::= Name

Name 表示标识符(见 §3.1)。

由于变量是 词法作用域(lexically scoped) 的, 局部变量可以被定义在其作用域内的函数自由访问 (见 §2.2)。

在对变量进行首次赋值之前,它的值为 nil

方括号用于索引表:

	var ::= prefixexp ‘[’ exp ‘]

访问表字段的含义可以通过元表改变 (见 §2.4)。

语法 var.Name 只是 var["Name"] 的语法糖:

	var ::= prefixexp ‘.’ Name

对全局变量 x 的访问 等价于 _ENV.x

3.3 – 语句

Lua 支持一组几乎常规的语句集合, 与其它传统语言类似。 该集合包括 代码块、赋值、控制结构、函数调用 和变量声明。

3.3.1 – 代码块

代码块是语句的列表, 按顺序执行:

	block ::= {stat}

Lua 有 空语句(empty statements), 允许你用分号分隔语句、 用分号开始一个代码块, 或连续写两个分号:

	stat ::= ‘;

函数调用和赋值 都可能以左括号开始。 这种可能性导致 Lua 语法中存在歧义。 考虑下面这段:

     a = b + c
     (print or io.write)('done')

语法可以把这段解析为两种方式:

     a = b + c(print or io.write)('done')
     
     a = b + c; (print or io.write)('done')

当前的解析器总是把这种构造视为 in the first way, interpreting the open parenthesis as the start of the arguments to a call. To avoid this ambiguity, it is a good practice to always precede with a semicolon statements that start with a parenthesis:

     ;(print or io.write)('done')

代码块可以用显式界定形成一个单独的语句:

	stat ::= do block end

显式代码块 有助于控制变量声明的作用域。 显式代码块有时也用于在另一个代码块中间 添加 return 语句(见 §3.3.4)。

3.3.2 – 代码块(Chunk)

Lua 的编译单元称为 chunk(代码块)。 从语法上讲, 一个 chunk 就是一个普通的块:

	chunk ::= block

Lua 把 chunk 当作一个匿名函数的函数体来处理, 该函数带有可变数量的参数 (见 §3.4.11)。 因此,chunk 可以定义局部变量、 接收参数并返回值。 此外,这个匿名函数是在一个名为 _ENV 的外部局部变量的作用域内编译的 (见 §2.2)。 最终得到的函数总是以 _ENV 作为它唯一的外部变量, 即便它并未使用该变量。

一个 chunk 可以存储在文件中, 或存储在宿主程序内的字符串里。 要执行一个 chunk, Lua 首先 加载(load) 它, 把 chunk 的代码预编译成虚拟机的指令, 然后 Lua 用一个针对该虚拟机的解释器执行编译后的代码。

chunk 也可以被预编译成二进制形式; 详见程序 luac 和函数 string.dump。 源代码形式和编译形式的程序是可互换的; Lua 会自动检测文件类型并做相应处理(见 load)。 请注意,与源代码不同, 被恶意构造的二进制 chunk 可能会使解释器崩溃。

3.3.3 – 赋值

Lua 允许多重赋值。 因此,赋值的语法 在左侧定义一个变量列表, 在右侧定义一个表达式列表。 两个列表中的元素都用逗号分隔:

	stat ::= varlist ‘=’ explist
	varlist ::= var {‘,’ var}
	explist ::= exp {‘,’ exp}

表达式将在 §3.4 中讨论。

在赋值之前, 值列表会被 调整(adjusted) 到 变量列表的长度(见 §3.4.12)。

如果一个变量在多重赋值中既被赋值又被读取, Lua 保证所有读取都得到该变量 在赋值之前的取值。 因此,下面这段代码

     i = 3
     i, a[i] = i+1, 20

会把 a[3] 设为 20,而不影响 a[4], 因为 a[i] 中的 i 在被赋值为 4 之前 先被求值(为 3)。 Similarly, the line

     x, y = y, x

交换 xy 的值, and

     x, y, z = y, z, x

循环置换 xyz 的值。

注意,这一保证只覆盖 在语法上位于赋值语句内部的访问。 如果在赋值过程中调用的某个函数或元方法 改变了某个变量的值, Lua 不保证该访问的顺序。

对全局名 x = val 的赋值 等价于赋值 _ENV.x = val(见 §2.2)。

对表字段和全局变量 (它们实际上也是表字段)的赋值的含义 可以通过元表改变(见 §2.4)。

3.3.4 – 控制结构

控制结构 ifwhilerepeat 具有通常的含义和熟悉的语法:

	stat ::= while exp do block end
	stat ::= repeat block until exp
	stat ::= if exp then block {elseif exp then block} [else block] end

Lua 还有 for 语句,有两种形式(见 §3.3.5)。

控制结构的条件表达式可以返回任意值。 falsenil 都会测试为假。 所有不同于 nilfalse 的值都测试为真。 特别地,数字 0 和空字符串同样测试为真。

repeatuntil 循环中, 内层块并不在 until 关键字处结束, 而是在条件之后才结束。 因此,条件可以引用 在循环块内部声明的局部变量。

goto 语句将程序控制转移到某个标签。 出于语法原因, Lua 中的标签也被视为语句:

	stat ::= goto Name
	stat ::= label
	label ::= ‘::’ Name ‘::

标签在它被定义的整个块内可见, 嵌套函数内部除外。 只要不进入某个变量声明的作用域, goto 可以跳转到任意可见的标签。 不应在已可见的同名标签处 再次声明标签, 即便那个标签是在外层块中声明的。

break 语句终止 whilerepeatfor 循环的执行, 跳到循环之后的下一条语句:

	stat ::= break

一个 break 结束最内层包围它的循环。

return 语句用于从函数或 chunk (被当作匿名函数处理)返回值。 函数可以返回多个值, 因此 return 语句的语法是

	stat ::= return [explist] [‘;’]

return 语句只能写在一个块的 最后一条语句处。 如果必须在块中间 return, 可以使用一个显式的内层块, 如习惯写法 do return end, 因为此时 return 是它(内层)块中的最后一条语句。

3.3.5 – For 语句

for 语句有两种形式: 一种数值形式,一种泛型形式。

数值 for 循环

数值 for 循环 repeats a block of code while a control variable goes through an arithmetic progression. It has the following syntax:

	stat ::= for Name ‘=’ exp ‘,’ exp [‘,’ exp] do block end

给定的标识符(Name)定义了控制变量, 它是一个新创建的、只读(const)的变量, 局部于循环体(block)。

循环开始时,先对三个控制表达式各求值一次。 它们的值分别称为 初值(initial value)上限(limit)步长(step)。 若步长缺失,则默认为 1。

如果初值和步长都是整数, 循环就以整数方式进行; 注意上限可以不是整数。 否则,三个值会被转换为浮点数, 循环以浮点数方式进行。 这种情况下要当心浮点精度问题。

初始化之后, 循环体被重复执行,控制变量的值 从初值开始,按步长给定的公差经历一个等差数列。 负的步长产生递减序列; 步长等于零会抛出错误。 只要控制变量的值小于或等于上限, (负步长时则为大于或等于) 循环就继续。 如果初值已经大于上限 (或小于上限,当步长为负时), 循环体不会被执行。

对于整数循环, 控制变量不会环绕; 相反,在发生溢出时循环结束。

泛型 for 循环

The generic for statement works over functions, called iterators. On each iteration, the iterator function is called to produce a new value, stopping when this new value is nil. 泛型 for 循环 has the following syntax:

	stat ::= for namelist in explist do block end
	namelist ::= Name {‘,’ Name}

像下面这样的 for 语句

     for var_1, ···, var_n in explist do body end

工作方式如下。

名字 var_i 声明了局部于循环体的循环变量。 其中第一个变量是 控制变量(control variable), 它是一个只读(const)变量。

循环开始时先对 explist 求值, 产生四个值: 一个 迭代器函数(iterator function)、 一个 状态(state)、 控制变量的初值, 以及一个 关闭值(closing value)

然后,在每次迭代中, Lua 用两个参数调用迭代器函数: 状态和当前控制变量。 这次调用的结果随后被赋给循环变量, 遵循多重赋值的规则(见 §3.3.3)。 如果控制变量变为 nil, 循环终止。 否则,执行循环体,并进入下一次迭代。

关闭值表现得像 一个“待关闭”变量(见 §3.3.8), 可用于在循环结束时释放资源。 除此之外,它不影响循环。

3.3.6 – 作为语句的函数调用

为了允许可能的副作用, 函数调用可以作为语句执行:

	stat ::= functioncall

这种情况下,所有返回值都被丢弃。 函数调用在 §3.4.10 中说明。

3.3.7 – 变量声明

局部变量和全局变量可以在块内任何地方声明。 声明可以包含初始化:

	stat ::= local attnamelist [‘=’ explist]
	stat ::= global attnamelist [‘=’ explist]

如果没有初始化, 局部变量会被初始化为 nil; 全局变量保持不变。 否则,初始化按多重赋值的同样方式 进行调整(见 §3.3.3)。 此外,对于全局变量, 如果该变量已经定义(即它有一个非 nil 的值), 初始化会抛出一个运行时错误。

名字列表可以用一个属性 (尖括号之间的名字)作前缀, 并且每个变量名也可以用属性作后缀:

	attnamelist ::=  [attrib] Name [attrib] {‘,’ Name [attrib]}
	attrib ::= ‘<’ Name ‘>

前缀属性作用于列表中的所有名字; 后缀属性只作用于它对应的那个名字。 有两种可能的属性: const,声明一个 常量(constant)只读(read-only) 变量, 即一个不能被用作赋值 左值的变量; 以及 close,声明一个“待关闭”变量(见 §3.3.8)。 只有局部变量才能拥有 close 属性。 一个变量列表中至多只能包含一个“待关闭”变量。

Lua 还提供了一种对全局变量的批量声明:

	stat ::= global [attrib] ‘*

这种特殊形式会隐式地把 所有此前未显式声明的名字声明为全局。 特别地, global<const> * 会隐式地把 所有此前未显式声明的名字声明为只读全局; see the following example:

     global X
     global<const> *
     print(math.pi)   -- Ok, 'print' and 'math' are read-only
     X = 1            -- Ok, declared as read-write
     Y = 1            -- Error, Y is read-only

§2.2 所述, 所有 chunk 都以一个隐式声明 global * 开始, 但这个前缀声明在 任何其它 global 声明的作用域内失效。 因此,一个不使用全局声明 或不以 global * 开头的程序 对所有全局变量拥有自由的读写访问权限; 以 global<const> * 开头的程序 对所有全局变量拥有自由的只读访问权限; 而以任何其它全局声明开头的程序 (例如 global none)只能引用已声明的变量。

注意,对于全局变量, 任何声明的作用都仅是语法层面的 (可选赋值除外):

     global X <const>, _G
     X = 1           -- ERROR
     _ENV.X = 1      -- Ok
     _G.print(X)     -- Ok
     foo()           -- 'foo' can freely change any global

chunk 本身也是一个块(见 §3.3.2), 因此变量可以在 chunk 中、任何显式块之外声明。

变量声明的可见性规则 在 §2.2 中说明。

3.3.8 – 待关闭变量

“待关闭”变量的行为类似于常量局部变量, 区别在于:无论何时变量离开作用域—— 包括正常的块终止、 通过 break/goto/return 退出其块, 或通过错误退出——其值都会被 关闭(closed)

这里,关闭 一个值是指 调用它的 __close 元方法。 调用该元方法时, 值本身作为第一个参数传入。 如果发生了错误, 导致退出的错误对象会作为第二个参数传入; 否则没有第二个参数。

赋给“待关闭”变量的值 必须拥有 __close 元方法, 或者是一个假值。 (nilfalse 作为“待关闭”值会被忽略。)

如果多个“待关闭”变量在同一事件下离开作用域, 它们会按照与声明相反的顺序被关闭。

如果在运行关闭方法时发生任何错误, 该错误会像定义该变量的常规代码中的错误一样被处理。 出错之后, 其它待处理的关闭方法仍会被调用。

如果一个协程让出后再也没有被恢复, 某些变量可能永远不离开作用域, 从而永远不会被关闭。 (这些变量是协程内部创建、 且在其让出点仍处于作用域中的那些变量。) 类似地,如果一个协程以错误结束, 它不会展开其栈, 因此也不会关闭任何变量。 在这两种情况下, 你可以使用终结器, 或者调用 coroutine.close 来关闭这些变量。 不过,如果协程是通过 coroutine.wrap 创建的, 那么其对应的函数会在出错时关闭该协程。

3.4 – 表达式

Lua 中的基本表达式如下:

	exp ::= prefixexp
	exp ::= nil | false | true
	exp ::= Numeral
	exp ::= LiteralString
	exp ::= functiondef
	exp ::= tableconstructor
	exp ::= ‘...’
	exp ::= exp binop exp
	exp ::= unop exp
	prefixexp ::= var | functioncall | ‘(’ exp ‘)

数字和字面量字符串在 §3.1 中说明; 变量在 §3.2 中说明; 函数定义在 §3.4.11 中说明; 函数调用在 §3.4.10 中说明; 表构造器在 §3.4.9 中说明。 由三个点('...')表示的 Vararg 表达式 只能在可变参数函数内部直接使用; 它们在 §3.4.11 中说明。

二元运算符包括算术运算符(见 §3.4.1)、 按位运算符(见 §3.4.2)、 关系运算符(见 §3.4.4)、逻辑运算符(见 §3.4.5), 以及连接运算符(见 §3.4.6)。 一元运算符包括一元负号(见 §3.4.1)、 一元按位 NOT(见 §3.4.2)、 一元逻辑 not(见 §3.4.5), 以及一元 长度运算符(length operator)(见 §3.4.7)。

3.4.1 – 算术运算符

Lua 支持以下算术运算符:

除乘方和浮点除法外, 算术运算符的工作方式如下: 如果两个操作数都是整数, 则在整数上执行运算,结果为整数。 否则,如果两个操作数都是数字, 则它们被转换为浮点数, 运算按机器浮点运算规则 (通常是 IEEE 754 标准)执行, 结果为浮点数。 (字符串库在算术运算中会把字符串强制转换为数字; 详见 §3.4.3。)

乘方和浮点除法(/) 总是把操作数转换为浮点数, 结果也总是浮点数。 乘方使用 ISO C 函数 pow, 因此它也适用于非整数指数。

向下取整除法(//)是一种 把商向负无穷方向取整的除法, 结果是其操作数相除后的下取整。

取模定义为 把商向负无穷方向取整(向下取整除法)后所得的余数。

在整数算术发生溢出时, 所有运算都会 环绕(wrap around)

3.4.2 – 按位运算符

Lua 支持以下按位运算符:

所有按位运算都把操作数转换为整数 (见 §3.4.3), 对这些整数的所有位进行操作, 结果为整数。

右移和左移都用零填充空出的位。 负的位移量向相反方向移动; 当位移量的绝对值等于或大于 整数位数时,结果为零(因为所有位都被移出)。

3.4.3 – 强制转换与类型转换

Lua 在运行时会提供一些类型与表示之间的自动转换。 按位运算符总是把浮点操作数转换为整数。 乘方和浮点除法 总是把整数操作数转换为浮点数。 应用于混合数字(整数与浮点数)的所有其它算术运算 会把整数操作数转换为浮点数。 C API 也会按需把整数转换为浮点数、 把浮点数转换为整数。 此外,字符串连接除了字符串外,也接受数字作为参数。

在整数到浮点数的转换中, 如果整数值可以精确表示为浮点数, 结果就是该精确值。 否则,转换会取相邻的较高或较低的可表示值。 这种转换永远不会失败。

从浮点数到整数的转换 会检查该浮点数是否能精确表示为整数 (即该浮点数为整数值, 且处于整数可表示范围内)。 如果是,则该表示即为结果。 否则,转换失败。

Lua 中多处会在必要时把字符串强制转换为数字。 特别地, 字符串库设置了元方法, 尝试在所有算术运算中把字符串强制转换为数字。 如果转换失败, 该库会调用另一个操作数的元方法 (若存在),否则抛出错误。 注意,按位运算符不做这种强制转换。

最好不要依赖 字符串到数字的隐式强制转换, 因为它们并非总是被应用; 特别地,"1"==1 为假,而 "1"<1 会抛出错误 (见 §3.4.4)。 这些强制转换主要是为了兼容性而存在, 可能在语言未来的版本中被移除。

字符串到整数或浮点数的转换 遵循其语法以及 Lua 词法分析器的规则。 字符串前后可以带有空白字符和符号。 所有从字符串到数字的转换 都同时接受点号和当前区域设置的小数点标记 作为基数分隔符。 (不过,Lua 词法分析器只接受点号。) 如果字符串不是合法的数值, 转换失败。 如有必要,第一步的结果会再根据 前面浮点与整数之间转换的规则, 转换为特定的数字子类型。

从数字到字符串的转换使用一种 未指定的、人类可读的格式。 若要以任何特定方式把数字转换为字符串, 请使用函数 string.format

3.4.4 – 关系运算符

Lua 支持以下关系运算符:

这些运算符的结果总是 falsetrue

等于(==)首先比较其操作数的类型。 如果类型不同,结果为 false。 否则,比较操作数的值。 若两个字符串的字节内容相同,则它们相等。 若两个数字表示相同的数学值,则它们相等。

表、userdata 和线程 按引用比较: 两个对象只有在是同一个对象时才被认为相等。 每次你创建一个新对象 (表、userdata 或线程), 这个新对象都不同于任何先前已存在的对象。 函数总是与自身相等。 任何可察觉不同的函数 (行为不同、定义不同)总是不同的。 在不同时刻创建、但没有可察觉差异的函数 可能被判定为相等或不相等 (取决于内部缓存细节)。

你可以通过 __eq 元方法 改变 Lua 比较表和 userdata 的方式 (见 §2.4)。

等于比较不会把字符串转换为数字, 也不会反过来转换。 因此,"0"==0 求值为 false, 而 t[0]t["0"] 表示表中不同的条目。

运算符 ~= 正好等于等于(==)的否定。

顺序运算符的工作方式如下。 如果两个参数都是数字, 则按它们的数学值比较, 不论子类型。 否则,如果两个参数都是字符串, 则按当前区域设置比较它们的值。 否则,Lua 会尝试调用 __lt__le 元方法 (见 §2.4)。 比较 a > b 被翻译为 b < a, 而 a >= b 被翻译为 b <= a

根据 IEEE 754 标准, 特殊值 NaN 既不小于、 也不等于、 也不大于任何值,包括它自己。

3.4.5 – 逻辑运算符

Lua 中的逻辑运算符是 andornot。 与控制结构类似(见 §3.3.4), 所有逻辑运算符都把 falsenil 视为假, 把其它一切视为真。

否定运算符 not 总是返回 falsetrue。 合取运算符 and 在其第一个参数为 falsenil 时返回第一个参数; 否则返回第二个参数。 析取运算符 or 在其第一个参数不同于 nilfalse 时返回第一个参数; 否则返回第二个参数。 andor 都使用短路求值; 也就是说, 第二个操作数只在必要时才被求值。 下面是一些例子:

     10 or 20            --> 10
     10 or error()       --> 10
     nil or "a"          --> "a"
     nil and 10          --> nil
     false and error()   --> false
     false and nil       --> false
     false or nil        --> nil
     10 and 20           --> 20

3.4.6 – 连接

Lua 中的字符串连接运算符 用两个点('..')表示。 如果两个操作数都是字符串或数字, 则数字被转换为字符串, 使用未指定的格式(见 §3.4.3)。 否则,会调用 __concat 元方法(见 §2.4)。

3.4.7 – 长度运算符

长度运算符用一元前缀运算符 # 表示。

字符串的长度就是它的字节数。 (当每个字符为一个字节时,这就是字符串长度通常的含义。)

应用在一个表上的长度运算符 会返回该表中的一个边界(border)。 表 t 中的 边界 是指满足以下条件的任意非负整数:

     (border == 0 or t[border] ~= nil) and
     (t[border + 1] == nil or border == math.maxinteger)

换言之, 边界是表中存在的任意正整数索引, 且其后是缺失的索引, 再加上两种极限情况: 当索引 1 缺失时为 0; 当该索引存在时为整数的最大值。 注意,非正整数的键 不会影响边界。

只有一个边界的表称为 序列(sequence)。 例如,表 {10,20,30,40,50} 是一个序列, 因为它只有一个边界(5)。 表 {10,20,30,nil,50} 有两个边界(3 和 5), 因此它不是一个序列。 (索引 4 处的 nil 称为一个 空洞(hole)。) The table {nil,20,30,nil,nil,60,nil} has three borders (0, 3, and 6), so it is not a sequence, too. 表 {} 是一个边界为 0 的序列。

t 是一个序列时, #t 返回它唯一的边界, 这对应于序列长度这一直观概念。 当 t 不是序列时, #t 可以返回它的任意一个边界。 (具体返回哪个取决于 表内部表示的细节, 而后者又可能取决于表是如何被填充的、 以及其非数值键的内存地址。)

表长度的计算 保证最坏时间为 O(log n), 其中 n 是表中最大的整数键。

程序可以通过 __len 元方法 改变长度运算符对除字符串外任意值的行为 (见 §2.4)。

3.4.8 – 优先级

Lua 中运算符的优先级如下表所示, 从低到高:

     or
     and
     <     >     <=    >=    ~=    ==
     |
     ~
     &
     <<    >>
     ..
     +     -
     *     /     //    %
     unary operators (not   #     -     ~)
     ^

像通常一样, 你可以用括号来改变表达式中运算的优先级。 连接('..')和乘方('^') 运算符是右结合的。 其它所有二元运算符都是左结合的。

3.4.9 – 表构造器

表构造器是创建表的 expression。 每次对一个构造器求值,都会创建一个新表。 构造器可以用来创建一个空表, 或者创建一个表并初始化其中一些字段。 构造器的一般语法是

	tableconstructor ::= ‘{’ [fieldlist] ‘}’
	fieldlist ::= field {fieldsep field} [fieldsep]
	field ::= ‘[’ exp ‘]’ ‘=’ exp | Name ‘=’ exp | exp
	fieldsep ::= ‘,’ | ‘;

每个形如 [exp1] = exp2 的字段会向新表添加一个条目, 键为 exp1,值为 exp2。 形如 name = exp 的字段等价于 ["name"] = exp。 形如 exp 的字段等价于 [i] = exp, 其中 i 是从 1 开始的连续整数; 其它格式的字段不影响这个计数。 例如:

     a = { [f(1)] = g; "x", "y"; x = 1, f(x), [30] = 23; 45 }

is equivalent to

     do
       local t = {}
       t[f(1)] = g
       t[1] = "x"         -- 1st exp
       t[2] = "y"         -- 2nd exp
       t.x = 1            -- t["x"] = 1
       t[3] = f(x)        -- 3rd exp
       t[30] = 23
       t[4] = 45          -- 4th exp
       a = t
     end

构造器中赋值的顺序未定义。 (这个顺序只有在出现重复键时才有意义。)

如果列表的最后一个字段是 exp 形式, 且该表达式是一个多返回值(multires)表达式, 那么该表达式返回的所有值会依次进入列表 (见 §3.4.12)。

字段列表可以带一个可选的尾部分隔符, 以方便机器生成的代码。

3.4.10 – 函数调用

Lua 中的函数调用语法如下:

	functioncall ::= prefixexp args

在函数调用中, 首先求值 prefixexp 和 args。 如果 prefixexp 的值的类型是 function, 则调用该函数,并传入给定参数。 否则,若存在, 则调用 prefixexp 的 __call 元方法: 它的第一个参数是 prefixexp 的值, 后面跟着原始的调用参数 (见 §2.4)。

The form

	functioncall ::= prefixexp ‘:’ Name args

可用于模拟方法。 调用 v:name(args)v.name(v, args) 的语法糖, 区别在于 v 只被求值一次。

参数具有以下语法:

	args ::= ‘(’ [explist] ‘)’
	args ::= tableconstructor
	args ::= LiteralString

所有参数表达式都在调用之前求值。 形如 f{fields} 的调用是 f({fields}) 的语法糖; 也就是说,参数列表是一个单独的新表。 形如 f'string' (或 f"string"f[[string]]) 的调用是 f('string') 的语法糖; 也就是说,参数列表是一个单独的字符串字面量。

不在“待关闭”变量作用域内、 形如 return functioncall 的调用 称为 尾调用(tail call)。 Lua 实现了 正确的尾调用(proper tail calls) (或称 正确的尾递归(proper tail recursion)): 在尾调用中, 被调用函数会复用调用函数的栈帧。 因此,一个程序能执行的嵌套尾调用次数没有限制。 不过,尾调用会抹除 关于调用函数的任何调试信息。 注意,尾调用只发生在一种特定语法下, 即 return 以单个函数调用为参数, 且它不在任何“待关闭”变量的作用域内。 这种语法使调用函数恰好返回 被调用函数的返回值, 其间没有任何其它动作。 因此,下面这些例子都不是尾调用:

     return (f(x))        -- results adjusted to 1
     return 2 * f(x)      -- result multiplied by 2
     return x, f(x)       -- additional results
     f(x); return         -- results discarded
     return x or f(x)     -- results adjusted to 1

3.4.11 – 函数定义

函数定义的语法是

	functiondef ::= function funcbody
	funcbody ::= ‘(’ [parlist] ‘)’ block end

下面的语法糖简化了函数定义:

	stat ::= function funcname funcbody
	stat ::= local function Name funcbody
	stat ::= global function Name funcbody
	funcname ::= Name {‘.’ Name} [‘:’ Name]

The statement

     function f () body end

会被翻译为

     f = function () body end

The statement

     function t.a.b.c.f () body end

会被翻译为

     t.a.b.c.f = function () body end

The statement

     local function f () body end

会被翻译为

     local f; f = function () body end

而不是

     local f = function () body end

(只有当函数体中含有对 f 的递归引用时, 这才有区别。) Similarly, the statement

     global function f () body end

会被翻译为

     global f; global f = function () body end

第二个 global 使该赋值成为一次初始化, 如果该全局变量已经定义,则会抛出错误。

冒号 语法 用于模拟 方法(methods), 为函数添加一个隐式的额外参数 self。 因此,语句

     function t.a.b.c:f (params) body end

是以下形式的语法糖

     t.a.b.c.f = function (self, params) body end

函数定义是一个可执行的表达式, 其值类型为 function。 当 Lua 预编译一个 chunk 时, 它的所有函数体也都被预编译, 但它们尚未被创建。 然后,每当 Lua 执行函数定义时, 该函数被 实例化(instantiated)(或称 封闭(closed))。 这个函数实例,或称 闭包(closure), 就是该表达式的最终值。

结果通过 return 语句返回(见 §3.3.4)。 如果控制流到达函数末尾而没有遇到 return 语句, 那么该函数返回零个结果。

一个函数可以返回的值的数量 有一个依赖于系统的上限。 该上限保证至少为 1000。

参数

参数 act as local variables that are initialized with the argument values:

	parlist ::= namelist [‘,’ varargparam] | varargparam
	varargparam ::= ‘...’ [Name]

当一个 Lua 函数被调用时, 它会把实参列表 调整到形参列表的长度(见 §3.4.12), 除非该函数是 可变参数函数(variadic function), 其标志是参数列表末尾的三个点('...')。 可变参数函数不调整其实参列表; 相反,它收集所有多余实参, 并通过一个 变长参数表(vararg table) 提供给函数。 在该表中, 索引 1、2 等处的值是多余的实参, 索引 "n" 处的值是多余实参的数量。

作为例子,考虑以下定义:

     function f(a, b) end
     function g(a, b, ...) end
     function r() return 1,2,3 end

于是,我们得到以下从实参到形参、 以及到变长参数表的映射:

     CALL             PARAMETERS
     
     f(3)             a=3, b=nil
     f(3, 4)          a=3, b=4
     f(3, 4, 5)       a=3, b=4
     f(r(), 10)       a=1, b=10
     f(r())           a=1, b=2
     
     g(3)             a=3, b=nil, va. table ->  {n = 0}
     g(3, 4)          a=3, b=4,   va. table ->  {n = 0}
     g(3, 4, 5, 8)    a=3, b=4,   va. table ->  {5, 8, n = 2}
     g(5, r())        a=5, b=1,   va. table ->  {2, 3, n = 2}

可变参数函数中的变长参数表可以有一个可选的名字, 写在点号之后。 当存在该名字时, 它表示一个只读的局部变量, 指向变长参数表。 如果变长参数表没有名字, 它只能通过变长参数表达式访问。

变长参数表达式也写作三个点, 它的值是一个列表,包含变长参数表中 从 1 到索引 "n" 处整数值的值。 (因此,如果代码没有修改变长参数表, 这个列表就对应于函数调用中的多余实参。) 这个列表表现得像 一个多返回值函数的结果(见 §3.4.12)。

作为一种优化, 如果变长参数表满足某些条件, 代码不会创建实际的表, 而是把索引表达式和变长参数表达式 翻译成对内部变长参数数据的访问。 条件如下: 如果变长参数表有名字, 那么该名字不是嵌套函数中的 upvalue, 并且它只作为语法构造 t[exp]t.id 中的基表使用。 注意,匿名的变长参数表总是满足这些条件。

3.4.12 – 表达式列表、多返回值与调整

函数调用和变长参数表达式都可能产生多个值。 这些表达式被称为 多返回值表达式(multires expressions)

当一个多返回值表达式被用作 表达式列表的最后一个元素时, 该表达式产生的所有结果都会被加入 该列表所生成的值列表中。 注意,在期望一个表达式列表的位置上的 单个表达式, 就是该(单元素)列表中的最后一个表达式。

以下是 Lua 期望表达式列表的位置:

在后四种情况下, 表达式列表所生成的值列表 必须被 调整(adjusted) 到特定长度: 对非可变参数函数调用时的形参数量 (见 §3.4.11)、 多重赋值或声明中的变量数量, 以及泛型 for 循环的恰好四个值。 调整 遵循以下规则: 如果值多于所需,多余的值被丢弃; 如果值少于所需,列表用 nil 补足。 当表达式列表以一个多返回值表达式结尾时, 该表达式产生的所有结果会在调整之前进入值列表。

当一个多返回值表达式被用在 表达式列表中但不是最后一个元素, 或者用在语法期望单个表达式的位置时, Lua 会将该表达式的结果列表调整为单个元素。 作为一种特例, 括号表达式内部语法期望单个表达式; 因此,在多返回值表达式外加括号 会强制它恰好产生一个结果。

我们很少需要把变长参数表达式 用在语法期望单个表达式的位置。 (通常更简单的做法是: 在可变参数部分之前加一个普通参数并改用该参数。) 当确有这种需要时, 我们建议把变长参数表达式 赋给一个单独的变量,并在该处使用这个变量。

下面是使用多返回值表达式的一些例子。 在所有情况下,当构造需要 “第 n 个结果”而该结果不存在时, 它会使用 nil

     print(x, f())      -- prints x and all results from f().
     print(x, (f()))    -- prints x and the first result from f().
     print(f(), x)      -- prints the first result from f() and x.
     print(1 + f())     -- prints 1 added to the first result from f().
     local x = ...      -- x gets the first vararg argument.
     x,y = ...          -- x gets the first vararg argument,
                        -- y gets the second vararg argument.
     x,y,z = w, f()     -- x gets w, y gets the first result from f(),
                        -- z gets the second result from f().
     x,y,z = f()        -- x gets the first result from f(),
                        -- y gets the second result from f(),
                        -- z gets the third result from f().
     x,y,z = f(), g()   -- x gets the first result from f(),
                        -- y gets the first result from g(),
                        -- z gets the second result from g().
     x,y,z = (f())      -- x gets the first result from f(), y and z get nil.
     return f()         -- returns all results from f().
     return x, ...      -- returns x and all received vararg arguments.
     return x,y,f()     -- returns x, y, and all results from f().
     {f()}              -- creates a list with all results from f().
     {...}              -- creates a list with all vararg arguments.
     {f(), 5}           -- creates a list with the first result from f() and 5.

4 – 应用程序接口(C API)

本节描述 Lua 的 C API, 即宿主程序用来与 Lua 通信的一组 C 函数。 所有 API 函数及相关的类型和常量 都声明在头文件 lua.h 中。

即使我们使用“函数”一词, API 中的任何功能也可能以宏的形式提供。 除非另有说明, 所有这些宏对每个参数都只使用一次 (第一个参数总是 Lua 状态机除外), 因此不会产生任何隐藏的副作用。

与大多数 C 库一样, Lua 的 API 函数不会检查其参数的 有效性或一致性。 不过,你可以通过在编译 Lua 时 定义宏 LUA_USE_APICHECK 来改变这一行为。

Lua 库是完全可重入(reentrant)的: 它没有全局变量。 它把所有需要的信息都保存在一个动态结构中, 称为 Lua 状态机(Lua state)

每个 Lua 状态机有一个或多个线程, 它们对应于独立的、协作式的执行线。 类型 lua_State(尽管名字如此)指代一个线程。 (通过线程间接地,它也指代 与该线程关联的 Lua 状态机。)

指向线程的指针必须作为第一个参数传给库中每个函数, 例外是 lua_newstate, 它从零创建一个 Lua 状态机,并返回指向 新状态机中 主线程(main thread) 的指针。

4.1 –

Lua 使用一个 虚拟栈(virtual stack) 来在 C 与 Lua 之间传递值。 栈中的每个元素表示一个 Lua 值 (nil、number、string 等)。 API 中的函数可以通过它们接收到的 Lua 状态机参数来访问这个栈。

每当 Lua 调用 C 时,被调用的函数会得到一个新栈, 它独立于先前的栈以及 仍然活跃的 C 函数的栈。 这个栈最初包含传给 C 函数的实参, C 函数可以在其中存放临时 Lua 值, 并必须把结果压入栈中以返回给调用者 (见 lua_CFunction)。

为方便起见, API 中大多数查询操作并不遵循严格的栈纪律。 相反,它们可以通过 索引(index) 引用栈中的任意元素: 正索引表示绝对栈位置, 以 1 作为栈底; 负索引表示相对于栈顶的偏移。 更具体地说,如果栈有 n 个元素, 那么索引 1 表示第一个元素 (即最先被压入栈的元素), 而索引 n 表示最后一个元素; 索引 -1 同样表示最后一个元素 (即位于栈顶的元素), 索引 -n 表示第一个元素。

4.1.1 – 栈大小

当你与 Lua API 交互时, 你有责任保证一致性。 特别地, 你有责任控制栈溢出。 当你调用任何 API 函数时, 必须确保栈有足够的空间容纳结果。

上述规则有一个例外: 当你调用一个结果数量不固定的 Lua 函数时 (见 lua_call), Lua 会确保栈有足够空间容纳所有结果。 但它不保证任何额外空间。 因此,在此类调用之后、向栈中压入任何东西之前, 你应该先使用 lua_checkstack

每当 Lua 调用 C 时, 它确保栈至少有 LUA_MINSTACK 个额外元素的空间; 也就是说,你可以安全地向其中压入最多 LUA_MINSTACK 个值。 LUA_MINSTACK 定义为 20, 因此通常你不必担心栈空间, 除非你的代码中有把元素压入栈的循环。 只要有需要, 你可以使用函数 lua_checkstack 来确保栈有足够空间压入新元素。

4.1.2 – 有效索引与可接受索引

API 中任何接收栈索引的函数 都只与 有效索引(valid indices)可接受索引(acceptable indices) 配合使用。

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

不需要特定可变位置、 而只需要一个值(例如查询函数)的函数, 可以用可接受索引调用。 可接受索引 可以是任何有效索引, 但也可以是栈顶之后、 在栈分配空间内的任意正索引, 即直到栈大小为止的索引。 (注意,0 永远不是可接受索引。) 指向 upvalues(见 §4.2)且大于当前 C 函数中 实际 upvalue 数量的索引也是可接受的(但无效)。 除非另有说明, API 中的函数都使用可接受索引。

可接受索引的作用是在查询栈时 避免对栈顶的额外测试。 例如,一个 C 函数可以查询它的第三个参数, 而无需检查是否存在第三个参数, 即无需检查 3 是否为有效索引。

对于可以用可接受索引调用的函数, 任何非有效索引都被当作 含有虚拟类型 LUA_TNONE 的值, 该类型表现得像 nil 值。

4.1.3 – 指向字符串的指针

API 中的多个函数带有 指向 C 字符串(const char*)的参数。 其中一些参数带有相关联的长度(size_t)。 除非另有说明, 当有相关联长度时, 字符串可以包含内嵌的零; 此外,若长度为 0,指针可以为 NULL。 当没有相关联长度时, 指针必须指向一个以零结尾的字符串。 无论如何,字符串内容在函数返回之前 都应保持不变。

API 中还有多个函数返回指向栈中 Lua 字符串的指针(const char*)。 (见 lua_pushfstringlua_pushlstringlua_pushstringlua_tolstring。 另见辅助库中的 luaL_checklstringluaL_checkstringluaL_tolstring。)

一般来说, Lua 的垃圾回收可以释放或移动内存, 从而使指向 Lua 状态机所处理字符串的指针失效。 为了安全地使用这些指针, API 保证:只要栈索引处的字符串值未被从栈中移除, 指向该索引字符串的指针就是有效的。 (不过它可以被移到另一个索引。) 当索引是伪索引(指向一个 upvalue)时, 只要相应的调用处于活跃状态、 且相应的 upvalue 未被修改,指针就有效。

调试接口中的一些函数 也会返回指向字符串的指针, 即 lua_getlocallua_getupvaluelua_setlocallua_setupvalue。 对于这些函数,指针保证在调用者函数活跃、 且给定的闭包(如果提供了)位于栈中时有效。

除这些保证外, 垃圾回收器可以自由地使 任何指向内部字符串的指针失效。

4.2 – C 闭包

当一个 C 函数被创建时, 可以把一些值与它关联起来, 从而创建一个 C 闭包(C closure) (见 lua_pushcclosure); 这些值称为 upvalues, 在函数每次被调用时都可访问。

每当一个 C 函数被调用时, 它的 upvalues 位于特定的伪索引处。 这些伪索引由宏 lua_upvalueindex 产生。 与函数关联的第一个 upvalue 在索引 lua_upvalueindex(1) 处,依此类推。 对任何 lua_upvalueindex(n) 的访问, 其中 n 大于当前函数的 upvalue 数量 (但不大于 256,即闭包中 upvalue 最大数量加一), 会产生一个可接受但无效的索引。

一个 C 闭包也可以修改其对应 upvalues 的值。

4.3 – 注册表

Lua 提供了一个 注册表(registry), 这是一个预定义的表,任何 C 代码都可以用它来 存储任何需要存储的 Lua 值。 注册表表始终可通过伪索引 LUA_REGISTRYINDEX 访问。 任何 C 库都可以把数据存入这个表, 但必须注意选择与其它库所用不同的键, 以避免冲突。 通常,你应该使用一个包含你库名的字符串作为键, 或者使用你代码中某个 C 对象地址的 light userdata, 或者你代码创建的任何 Lua 对象。 与变量名类似, 以下划线开头后接大写字母的字符串键是保留给 Lua 的。

注册表中的整数键被 引用机制(见 luaL_ref)使用, 带有一些预定义的值。 因此,注册表中的整数键 不得用于其它目的。

当你创建一个新的 Lua 状态机时, 它的注册表带有一些预定义的值。 这些预定义值以 lua.h 中定义为常量的整数键索引。 定义了以下常量:

4.4 – C 中的错误处理

在内部,Lua 使用 C 的 longjmp 机制来处理错误。 (如果你把 Lua 编译为 C++,它会使用异常; 详情请在源代码中搜索 LUAI_THROW。) 当 Lua 遇到任何错误, 例如内存分配错误或类型错误, 它会 抛出(raise) 一个错误; 即执行一次 long jump。 受保护环境(protected environment) 使用 setjmp 设置一个恢复点; 任何错误都会跳到最近的活动恢复点。

在 C 函数内部,你可以通过调用 lua_error 显式抛出一个错误。

API 中大多数函数都可能抛出错误, 例如由于内存分配错误。 每个函数的文档会说明它是否会抛出错误。

如果错误发生在任何受保护环境之外, Lua 会调用一个 panic 函数(panic function)(见 lua_atpanic), 然后调用 abort, 从而退出宿主应用程序。 你的 panic 函数可以通过永不返回 (例如,做一个 long jump 到你 Lua 之外的恢复点) 来避免这种退出。

顾名思义, panic 函数是一种最后的手段机制。 程序应该避免使用它。 作为一般规则, 当一个 C 函数被 Lua 带着某个 Lua 状态机调用时, 它可以在该状态机上做任何事, 因为它应该已经被保护。 然而, 当 C 代码操作其它 Lua 状态机时 (例如函数的一个 Lua 状态机参数、 存放在注册表中的 Lua 状态机, 或 lua_newthread 的结果), 它应该只在不会抛出错误的 API 调用中使用它们。

panic 函数运行起来就像它是一个消息处理器(见 §2.3); 特别地,错误对象位于栈顶。 但是,不能保证栈空间。 要在栈上压入任何东西, panic 函数必须首先检查可用空间(见 §4.1.1)。

4.4.1 – 状态码

API 中一些报告错误的函数使用以下 状态码来指示不同类型的错误或其它情况:

这些常量定义在头文件 lua.h 中。

4.5 – 在 C 中处理让出

在内部,Lua 使用 C 的 longjmp 机制来让出一个协程。 因此,如果一个 C 函数 foo 调用了一个 API 函数, 而这个 API 函数让出了 (直接或间接地通过调用另一个会让人出的函数), Lua 就无法再返回到 foo, 因为 longjmp 把它在 C 栈中的帧移除了。

为避免这类问题, Lua 在试图跨越 API 调用让出时会抛出一个错误, 但有三个函数例外: lua_yieldklua_callklua_pcallk。 这些函数都接收一个 延续函数(continuation function) (名为 k 的参数),用于在让出之后继续执行。

我们需要先定义一些术语来解释延续。 我们有一个从 Lua 调用的 C 函数, 我们称之为 原函数(original function)。 这个原函数接着调用 C API 中那三个函数之一, 我们称之为 被调用函数(callee function), 它随后会让出当前线程。 当被调用函数是 lua_yieldk 时, 或者被调用函数是 lua_callklua_pcallk、 且它们所调用的函数让出了时,就会发生这种情况。

假设运行中的线程在执行被调用函数时让出了。 线程恢复后, 最终会运行完被调用函数。 然而, 被调用函数无法返回到原函数, 因为它在 C 栈中的帧已被让出销毁。 相反,Lua 会调用一个 延续函数(continuation function), 它是作为被调用函数的参数给出的。 顾名思义, 延续函数应当继续原函数的任务。

作为示例,考虑下面这个函数:

     int original_function (lua_State *L) {
       ...     /* code 1 */
       status = lua_pcall(L, n, m, h);  /* calls Lua */
       ...     /* code 2 */
     }

现在我们想允许 由 lua_pcall 运行的 Lua 代码能够让出。 首先,我们可以像下面这样重写我们的函数:

     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);
     }

在上述代码中, 新函数 k 是一个 延续函数(continuation function)(类型为 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);
     }

注意对延续函数的外部显式调用: Lua 只在需要时才会调用延续函数, 即发生错误或让出后恢复时。 如果被调用的函数正常返回、从未让出, lua_pcallk(和 lua_callk)也会正常返回。 (当然,在这种情况下,你可以不在原函数里调用延续函数, 而是直接在原函数内部做等价的工作。)

除了 Lua 状态机外, 延续函数还有另外两个参数: 调用的最终状态和最初传给 lua_pcallk 的上下文值(ctx)。 Lua 不使用这个上下文值; 它只是把这个值从原函数传递给延续函数。 对于 lua_pcallk, 状态是 lua_pcallk 会返回的那个值, 区别只在于:在让出后执行时它是 LUA_YIELD (而不是 LUA_OK)。 对于 lua_yieldklua_callk, 当 Lua 调用延续函数时,状态总是 LUA_YIELD。 (对于这两个函数, Lua 在出错时不会调用延续函数, 因为它们不处理错误。) 类似地,使用 lua_callk 时, 你应该以 LUA_OK 作为状态来调用延续函数。 (对于 lua_yieldk,直接调用延续函数意义不大, 因为 lua_yieldk 通常不会返回。)

Lua 把延续函数当作原函数一样对待。 延续函数接收到与原函数相同的 Lua 栈, 其状态就如同被调用函数已经返回。 (例如,在 lua_callk 之后, 函数和其实参会从栈中移除,并被调用的结果取代。) 它也有相同的 upvalues。 它返回的任何值都会被 Lua 当作原函数的返回值来处理。

4.6 – 函数与类型

这里按字母顺序列出 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.


lua_absindex

[-0, +0, –]

int lua_absindex (lua_State *L, int idx);

把可接受索引 idx 转换为等价的绝对索引 (即不依赖于栈大小的索引)。


lua_Alloc

typedef void * (*lua_Alloc) (void *ud,
                             void *ptr,
                             size_t osize,
                             size_t nsize);

Lua 状态机所使用的内存分配器函数的类型。 该分配器函数必须提供 类似于 realloc 的功能, 但不完全相同。 它的参数是: ud,传给 lua_newstate 的不透明指针; ptr,指向正在被分配/重分配/释放的块的指针; osize,块的原始大小,或关于正在被分配对象的某种编码; 以及 nsize,块的新大小。

ptr 不为 NULL 时, osizeptr 所指向块的大小, 即分配或重分配时给定的大小。

ptrNULL 时, osize 编码了 Lua 正在分配的对象种类。 当且仅当 Lua 正在创建该类型的新对象时, osizeLUA_TSTRINGLUA_TTABLELUA_TFUNCTIONLUA_TUSERDATALUA_TTHREAD 之一。 当 osize 是其它值时, Lua 正在为别的东西分配内存。

Lua 期望分配器函数具有以下行为:

nsize 为零时, 分配器必须表现得像 free, 然后返回 NULL

nsize 不为零时, 分配器必须表现得像 realloc。 特别地,当且仅当无法满足请求时, 分配器才返回 NULL

下面是一个简单的分配器函数实现, 对应辅助库中的函数 luaL_alloc

     void *luaL_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);
     }

注意,ISO C 保证 free(NULL) 没有效果, 且 realloc(NULL,size) 等价于 malloc(size)


lua_arith

[-(2|1), +1, e]

void lua_arith (lua_State *L, int op);

对栈顶的两个值 (一元负号时为其中一个) 执行算术或按位运算, 其中栈顶的值为第二个操作数, 弹出这些值,并压入运算结果。 该函数遵循相应 Lua 运算符的语义 (即它可能调用元方法)。

op 的值必须是下列常量之一:


lua_atpanic

[-0, +0, –]

lua_CFunction lua_atpanic (lua_State *L, lua_CFunction panicf);

设置一个新的 panic 函数并返回旧的那个(见 §4.4)。


lua_call

[-(nargs+1), +nresults, e]

void lua_call (lua_State *L, int nargs, int nresults);

调用一个函数。 与常规 Lua 调用一样, lua_call 遵循 __call 元方法。 因此,此处的“函数”一词 指任何可调用的值。

进行调用必须使用以下协议: 首先,把要调用的函数压入栈; 然后,按直接顺序压入调用的参数; 即第一个参数先压入。 最后你调用 lua_callnargs 是你压入栈的参数个数。 当函数返回时, 所有参数和函数值被弹出, 调用的结果被压入栈。 结果的数量被调整为 nresults, 除非 nresultsLUA_MULTRET, 此时函数的所有结果都会被压入。 第一种情况(显式结果数量)下, 调用者必须保证栈有空间容纳返回值。 第二种情况下,Lua 负责让返回值适配栈空间, 但不保证栈上任何额外空间。 函数结果按直接顺序压入栈 (第一个结果先压入), 因此调用后最后一个结果位于栈顶。

nresults 的最大值是 250。

调用和运行该函数期间的任何错误都会向上传播 (通过 longjmp)。

下面的例子展示了宿主程序如何实现 与这段 Lua 代码等价的功能:

     a = f("how", t.x, 14)

以下是 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' */

注意上面的代码是 平衡(balanced) 的: 结束时栈恢复到最初的配置。 这被认为是良好的编程实践。


lua_callk

[-(nargs + 1), +nresults, e]

void lua_callk (lua_State *L,
                int nargs,
                int nresults,
                lua_KContext ctx,
                lua_KFunction k);

这个函数的行为与 lua_call 完全一致, 但允许被调用的函数让出(见 §4.5)。


lua_CFunction

typedef int (*lua_CFunction) (lua_State *L);

C 函数的类型。

为了与 Lua 正确通信, 一个 C 函数必须使用以下协议, 它定义了参数和结果的传递方式: C 函数从 Lua 的栈中按直接顺序接收参数 (第一个参数先被压入)。 因此,当函数开始时, lua_gettop(L) 返回函数收到的参数个数。 第一个参数(如果有)在索引 1 处, 最后一个参数在索引 lua_gettop(L) 处。 要向 Lua 返回值,C 函数只需把结果按直接顺序压入栈 (第一个结果先压入), 并在 C 中返回结果的数量。 栈中位于结果之下的其它值会被 Lua 正确地丢弃。 与 Lua 函数一样,被 Lua 调用的 C 函数也可以返回多个结果。

例如,下面的函数接收可变数量的数字参数, 并返回它们的平均值与总和:

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

确保栈至少有 n 个额外元素的空间, 即你可以安全地向其中压入最多 n 个值。 如果无法满足请求,它返回 false, 原因可能是会使栈超过固定的最大尺寸 (通常至少为几千个元素), 或无法为额外空间分配内存。 这个函数从不收缩栈; 如果栈已经有空间容纳额外元素, 它就保持不变。


lua_close

[-0, +0, –]

void lua_close (lua_State *L);

关闭主线程中所有活跃的“待关闭”变量, 释放给定 Lua 状态机中的全部对象 (如果存在相应的垃圾回收元方法则调用之), 并释放该状态机使用的所有动态内存。

在若干平台上,你可能不需要调用这个函数, 因为当宿主程序结束时所有资源会被自然释放。 另一方面,会创建多个状态机的长时间运行程序, 例如守护进程或 Web 服务器, 很可能需要在状态机不再需要时尽快关闭它们。


lua_closeslot

[-0, +0, e]

void lua_closeslot (lua_State *L, int index);

关闭给定索引处的“待关闭”槽,并将其值设为 nil。 该索引必须是先前被标记为待关闭、 且仍然活跃(即尚未关闭)的最后一个索引 (见 lua_toclose)。

通过这个函数调用时, __close 元方法不能让出。


lua_closethread

[-0, +?, –]

int lua_closethread (lua_State *L, lua_State *from);

重置一个线程,清空其调用栈并关闭所有待处理的 “待关闭”变量。 参数 from 表示正在重置 L 的协程。 如果没有这样的协程, 这个参数可以为 NULL

除非 L 等于 from, 否则调用返回一个状态码: LUA_OK 表示线程中没有错误 (无论是使线程停止的原始错误, 还是关闭方法中的错误), 否则为错误状态码。 出错时,错误对象被放在栈顶。

如果 L 等于 from, 则对应于线程关闭自身。 这种情况下, 调用不会返回; 相反,是(重新)启动该线程的 resume 返回。 线程必须运行在某个 resume 内部。


lua_compare

[-0, +0, e]

int lua_compare (lua_State *L, int index1, int index2, int op);

比较两个 Lua 值。 如果索引 index1 处的值在与索引 index2 处的值 比较时满足 op, 则遵循相应 Lua 运算符的语义返回 1 (即它可能调用元方法)。 否则返回 0。 如果任一索引无效,也返回 0。

op 的值必须是下列常量之一:


lua_concat

[-n, +1, e]

void lua_concat (lua_State *L, int n);

连接栈顶的 n 个值, 弹出它们,并把结果留在栈顶。 如果 n 为 1,结果就是栈上那个单独的值 (即该函数什么也不做); 如果 n 为 0,结果是空字符串。 连接遵循 Lua 的通常语义 (见 §3.4.6)。


lua_copy

[-0, +0, –]

void lua_copy (lua_State *L, int fromidx, int toidx);

把索引 fromidx 处的元素 复制到有效索引 toidx 处, 替换该位置的值。 其它位置的值不受影响。


lua_createtable

[-0, +1, m]

void lua_createtable (lua_State *L, int nseq, int nrec);

创建一个新空表并压入栈。 参数 nseq 是表将作为序列拥有的元素数量提示; 参数 nrec 是表将拥有的其它元素数量提示。 Lua 可能用这些提示为新表预分配内存。 当你预先知道表将有多少元素时, 这种预分配有助于性能。 否则你应该使用函数 lua_newtable


lua_dump

[-0, +0, –]

int lua_dump (lua_State *L,
                        lua_Writer writer,
                        void *data,
                        int strip);

把一个函数转储为二进制 chunk。 它接收栈顶的一个 Lua 函数, 产生一个二进制 chunk, 若再次加载该 chunk, 会得到一个与被转储函数等价的函数。 在生成 chunk 各部分时, lua_dump 会用给定的 data 调用函数 writer (见 lua_Writer)来写入它们。

函数 lua_dump 在对 writer 函数的调用过程中 完整地保留 Lua 栈, 唯一的例外是它可能在第一次调用前 压入一些供内部使用的值, 并在最后一次调用后把栈大小恢复到原始大小。

如果 strip 为真, 为了节省空间,二进制表示可能不包含 关于该函数的全部调试信息。

返回值是最后一次调用 writer 返回的错误码; 0 表示没有错误。


lua_error

[-1, +0, v]

int lua_error (lua_State *L);

抛出一个 Lua 错误, 使用栈顶的值作为错误对象。 这个函数执行一次 long jump, 因此永远不会返回 (见 luaL_error)。


lua_gc

[-0, +0, –]

int lua_gc (lua_State *L, int what, ...);

控制垃圾回收器。

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.

For more details about these options, see collectgarbage.

This function should not be called by a finalizer.


lua_getallocf

[-0, +0, –]

lua_Alloc lua_getallocf (lua_State *L, void **ud);

返回给定状态机的内存分配器函数。 如果 ud 不为 NULL,Lua 会把 设置内存分配器函数时给定的不透明指针存入 *ud


lua_getfield

[-0, +1, e]

int lua_getfield (lua_State *L, int index, const char *k);

把值 t[k] 压入栈, 其中 t 是给定索引处的值。 与 Lua 中一样,这个函数可能触发 "index" 事件的元方法(见 §2.4)。

返回被压入值的类型。


lua_getextraspace

[-0, +0, –]

void *lua_getextraspace (lua_State *L);

返回与给定 Lua 状态机关联的一块原始内存区域的指针。 应用程序可以把这块区域用于任何目的; Lua 不把它用于任何事情。

每个新线程的这块区域都初始化为主线程该区域的副本。

默认情况下,这块区域的大小等于一个 void 指针的大小, 但你可以用不同的大小重新编译 Lua。 (见 luaconf.h 中的 LUA_EXTRASPACE。)


lua_getglobal

[-0, +1, e]

int lua_getglobal (lua_State *L, const char *name);

把全局变量 name 的值压入栈。 返回该值的类型。


lua_geti

[-0, +1, e]

int lua_geti (lua_State *L, int index, lua_Integer i);

把值 t[i] 压入栈, 其中 t 是给定索引处的值。 与 Lua 中一样,这个函数可能触发 "index" 事件的元方法(见 §2.4)。

返回被压入值的类型。


lua_getmetatable

[-0, +(0|1), –]

int lua_getmetatable (lua_State *L, int index);

如果给定索引处的值有元表, 函数把该元表压入栈并返回 1。 否则,函数返回 0 且不在栈上压入任何东西。


lua_gettable

[-1, +1, e]

int lua_gettable (lua_State *L, int index);

把值 t[k] 压入栈, 其中 t 是给定索引处的值, k 是栈顶的值。

这个函数从栈中弹出键, 把结果值压回原来的位置。 与 Lua 中一样,这个函数可能触发 "index" 事件的元方法(见 §2.4)。

返回被压入值的类型。


lua_gettop

[-0, +0, –]

int lua_gettop (lua_State *L);

返回栈顶元素的索引。 因为索引从 1 开始, 这个结果等于栈中元素的数量; 特别地,0 表示空栈。


lua_getiuservalue

[-0, +1, –]

int lua_getiuservalue (lua_State *L, int index, int n);

把与给定索引处完整 userdata 关联的 第 n 个用户值压入栈, 并返回被压入值的类型。

如果 userdata 没有那个值, 则压入 nil 并返回 LUA_TNONE


lua_insert

[-1, +1, –]

void lua_insert (lua_State *L, int index);

把栈顶元素移到给定的有效索引处, 把该索引之上的元素向上移动以腾出空间。 这个函数不能用伪索引调用, 因为伪索引不是一个实际的栈位置。


lua_Integer

typedef ... lua_Integer;

Lua 中整数的类型。

默认情况下这个类型是 long long (通常是一个 64 位补码整数), 但也可以改成 longint (通常是一个 32 位补码整数)。 (见 luaconf.h 中的 LUA_INT_TYPE。)

Lua 还定义了常量 LUA_MININTEGERLUA_MAXINTEGER, 分别表示该类型能容纳的最小值和最大值。


lua_isboolean

[-0, +0, –]

int lua_isboolean (lua_State *L, int index);

如果给定索引处的值是布尔值,返回 1, 否则返回 0 。


lua_iscfunction

[-0, +0, –]

int lua_iscfunction (lua_State *L, int index);

如果给定索引处的值是 C 函数,返回 1, 否则返回 0 。


lua_isfunction

[-0, +0, –]

int lua_isfunction (lua_State *L, int index);

如果给定索引处的值是函数 (C 或 Lua),返回 1, 否则返回 0 。


lua_isinteger

[-0, +0, –]

int lua_isinteger (lua_State *L, int index);

如果给定索引处的值是整数 (即该值是数字且以整数表示),返回 1, 否则返回 0 。


lua_islightuserdata

[-0, +0, –]

int lua_islightuserdata (lua_State *L, int index);

如果给定索引处的值是 light userdata,返回 1, 否则返回 0 。


lua_isnil

[-0, +0, –]

int lua_isnil (lua_State *L, int index);

如果给定索引处的值是 nil,返回 1, 否则返回 0 。


lua_isnone

[-0, +0, –]

int lua_isnone (lua_State *L, int index);

如果给定索引无效,返回 1, 否则返回 0 。


lua_isnoneornil

[-0, +0, –]

int lua_isnoneornil (lua_State *L, int index);

如果给定索引无效, 或该索引处的值是 nil,返回 1, 否则返回 0 。


lua_isnumber

[-0, +0, –]

int lua_isnumber (lua_State *L, int index);

如果给定索引处的值是数字 或可转换为数字字符串,返回 1, 否则返回 0 。


lua_isstring

[-0, +0, –]

int lua_isstring (lua_State *L, int index);

如果给定索引处的值是字符串 或数字(数字总是可转换为字符串),返回 1, 否则返回 0 。


lua_istable

[-0, +0, –]

int lua_istable (lua_State *L, int index);

如果给定索引处的值是表,返回 1, 否则返回 0 。


lua_isthread

[-0, +0, –]

int lua_isthread (lua_State *L, int index);

如果给定索引处的值是线程,返回 1, 否则返回 0 。


lua_isuserdata

[-0, +0, –]

int lua_isuserdata (lua_State *L, int index);

如果给定索引处的值是 userdata (完整或轻量),返回 1, 否则返回 0 。


lua_isyieldable

[-0, +0, –]

int lua_isyieldable (lua_State *L);

如果给定协程可以让出,返回 1, 否则返回 0 。


lua_KContext

typedef ... lua_KContext;

延续函数上下文的类型。 它必须是数值类型。 当 intptr_t 可用时,它被定义为 intptr_t, 因此也能存储指针。 否则,它被定义为 ptrdiff_t


lua_KFunction

typedef int (*lua_KFunction) (lua_State *L, int status, lua_KContext ctx);

延续函数的类型(见 §4.5)。


lua_len

[-0, +1, e]

void lua_len (lua_State *L, int index);

返回给定索引处值的长度。 它等价于 Lua 中的 '#' 运算符(见 §3.4.7), 并可能触发 "length" 事件的元方法(见 §2.4)。 结果被压入栈。


lua_load

[-0, +1, –]

int lua_load (lua_State *L,
              lua_Reader reader,
              void *data,
              const char *chunkname,
              const char *mode);

加载一个 Lua chunk 但不运行它。 如果没有错误, lua_load 把编译后的 chunk 作为一个 Lua 函数压入栈顶。 否则,它压入一条错误消息。

lua_load 函数使用一个用户提供的 reader 函数 来读取 chunk(见 lua_Reader)。 data 参数是传给 reader 函数的不透明值。

The chunkname argument gives a name to the chunk, which is used for error messages and in debug information (see §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". Moreover, it may have a 'B' instead of a 'b', meaning a fixed buffer with the binary dump.

A fixed buffer means that the address returned by the reader function will contain the chunk until everything created by the chunk has been collected; therefore, Lua can avoid copying to internal structures some parts of the chunk. (In general, a fixed buffer would keep its contents until the end of the program, for instance with the chunk in ROM.) Moreover, for a fixed buffer, the reader function should return the entire chunk in the first read. (As an example, luaL_loadbufferx does that, which means that you can use it to load fixed buffers.)

The function lua_load fully preserves the Lua stack through the calls to the reader function, except that it may push some values for internal use before the first call, and it restores the stack size to its original size plus one (for the pushed result) after the last call.

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

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_newstate

[-0, +0, –]

lua_State *lua_newstate (lua_Alloc f, void *ud,
                                   unsigned int seed);

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. The third argument, seed, is a seed for the hashing of strings.


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

Threads are subject to garbage collection, like any Lua object.


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. The block of memory is suitably aligned for any ISO C object. (See macro LUAI_MAXALIGN in file luaconf.h for other alignment requirements.)

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

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.

This function may raise an error if the given key is neither nil nor present in the table.

See function next for more details about the traversal.


lua_Number

typedef ... lua_Number;

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

This macro may evaluate its arguments more than once.


lua_numbertocstring

[-0, +0, –]

unsigned lua_numbertocstring (lua_State *L, int idx,
                                        char *buff);

Converts the number at acceptable index idx to a string and puts the result in buff. The buffer must have a size of at least LUA_N2SBUFFSZ bytes. The conversion follows a non-specified format (see §3.4.3). The function returns the number of bytes written to the buffer (including the final zero), or zero if the value at idx is not a number.


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.

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.

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.

The lua_pcall function returns one of the following status codes: LUA_OK, LUA_ERRRUN, LUA_ERRMEM, or 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_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.


lua_pushboolean

[-0, +1, –]

void lua_pushboolean (lua_State *L, int b);

Pushes a boolean value with value b onto the stack.


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

Any function to be callable by Lua must follow the correct protocol to receive its parameters and return its results (see 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.

The maximum value for n is 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.


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.


lua_pushexternalstring

[-0, +1, m]

const char *lua_pushexternalstring (lua_State *L,
                const char *s, size_t len, lua_Alloc falloc, void *ud);

Creates an external string, that is, a string that uses memory not managed by Lua. The pointer s points to the external buffer holding the string content, and len is the length of the string. The string should have a zero at its end, that is, the condition s[len] == '\0' should hold. As with any string in Lua, the length must fit in a Lua integer.

If falloc is different from NULL, that function will be called by Lua when the external buffer is no longer needed. The contents of the buffer should not change before this call. The function will be called with the given ud, the string s as the block, the length plus one (to account for the ending zero) as the old size, and 0 as the new size.

Even when using an external buffer, Lua still has to allocate a header for the string. In case of a memory-allocation error, Lua will call falloc before raising the error.

The function returns a pointer to the string (that is, s).


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). The result is a copy of fmt with each conversion specifier replaced by a string representation of its respective extra argument. A conversion specifier (and its corresponding extra argument) can 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 void pointer), '%d' (inserts an int), '%c' (inserts an int as a one-byte character), and '%U' (inserts an unsigned long as a UTF-8 byte sequence).

Every occurrence of '%' in the string fmt must form a valid conversion specifier.

Besides memory allocation errors, this function may raise an error if the resulting string is too large.


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.


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_pushliteral

[-0, +1, v]

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_pushlstring

[-0, +1, v]

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.

Returns a pointer to the internal copy of the string (see §4.1.3).

Besides memory allocation errors, this function may raise an error if the string is too large.


lua_pushnil

[-0, +1, –]

void lua_pushnil (lua_State *L);

Pushes a nil value onto the stack.


lua_pushnumber

[-0, +1, –]

void lua_pushnumber (lua_State *L, lua_Number n);

Pushes a float with value n onto the stack.


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.

Returns a pointer to the internal copy of the string (see §4.1.3).

If s is NULL, pushes nil and returns 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.


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, –]

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, and it does not raise errors. Instead, in case of errors it pushes the error message and returns NULL.


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.


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

返回被压入值的类型。


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.

返回被压入值的类型。


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.


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

This function pops the value from the stack. The assignment is raw, that is, it does not use the __newindex metavalue.


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.

This function pops the value from the stack. The assignment is raw, that is, it does not use the __newindex metavalue.


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.


lua_register

[-0, +0, e]

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_resume

[-?, +?, –]

int lua_resume (lua_State *L, lua_State *from, int nargs,
                          int *nresults);

Starts and resumes a coroutine in the given thread 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. The function returns when the coroutine suspends, finishes its execution, or raises an unprotected error. When it returns without errors, *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 pushed on the top of the stack. (In that case, nresults is not updated, as its value would have to be 1 for the sole error object.)

To resume a suspended 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.

The parameter from represents the coroutine that is resuming L. If there is no such coroutine, this parameter can be 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.


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.


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.

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


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.

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


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

(For historical reasons, this function returns an int, which now is always 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.

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_settop

[-?, +?, e]

void lua_settop (lua_State *L, int index);

Receives any acceptable stack 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.

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

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_status

[-0, +0, –]

int lua_status (lua_State *L);

Returns the status of the thread 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.

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_stringtonumber

[-0, +(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.)


lua_toboolean

[-0, +0, –]

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


lua_toclose

[-0, +0, v]

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.

This function raises an error if the value at the given slot neither has a __close metamethod nor is a false value.

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.


lua_tointeger

[-0, +0, –]

lua_Integer lua_tointeger (lua_State *L, int index);

Equivalent to lua_tointegerx with isnum equal to 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.

If isnum is not NULL, its referent is assigned a boolean value that indicates whether the operation succeeded.


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

If len is not NULL, the function sets *len with the string length. The returned C string always has a zero ('\0') after its last character, but can contain other zeros in its body.

The pointer returned by lua_tolstring may be invalidated by the garbage collector if the corresponding Lua value is removed from the stack (see §4.1.3).

This function can raise memory errors only when converting a number to a string (as then it may create a new string).


lua_tonumber

[-0, +0, –]

lua_Number lua_tonumber (lua_State *L, int index);

Equivalent to lua_tonumberx with isnum equal to 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.

If isnum is not NULL, its referent is assigned a boolean value that indicates whether the operation succeeded.


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.

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


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


lua_Unsigned

typedef ... lua_Unsigned;

The unsigned version of 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].


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.

See warn for more details about warnings.


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.

See warn for more details about warnings.


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.

After lua_dump writes its last piece, it will signal that by calling the writer function one more time, with a NULL buffer (and size 0).

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.


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.


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

[-?, +?, 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.

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 all the results (nresults) removed and replaced by the arguments passed to lua_resume. Moreover, the continuation function receives the value ctx that was passed to lua_yieldk.

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.

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

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_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) */
  unsigned char extraargs;    /* (t) number of extra arguments */
  char istailcall;            /* (t) */
  int ftransfer;              /* (r) index of first value transferred */
  int 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.)

The fields of lua_Debug have the following meaning:


lua_gethook

[-0, +0, –]

lua_Hook lua_gethook (lua_State *L);

返回当前的 hook 函数。


lua_gethookcount

[-0, +0, –]

int lua_gethookcount (lua_State *L);

返回当前的 hook 计数。


lua_gethookmask

[-0, +0, –]

int lua_gethookmask (lua_State *L);

返回当前的 hook 掩码。


lua_getinfo

[-(0|1), +(0|1|2), m]

int lua_getinfo (lua_State *L, const char *what, lua_Debug *ar);

获取关于某个特定函数或其调用的信息。

要获取关于某次函数调用的信息, 参数 ar 必须是一个由先前对 lua_getstack 的调用 填充的、有效的活动记录, 或是作为 hook 的参数给出的(见 lua_Hook)。

要获取关于某个函数的信息,你把它压入栈, 并以字符 '>' 开始 what 字符串。 (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:

     lua_Debug ar;
     lua_getglobal(L, "f");  /* get global 'f' */
     lua_getinfo(L, ">S", &ar);
     printf("%d\n", ar.linedefined);

字符串 what 中的每个字符 会选择结构 ar 中某些要被填充的字段, 或要压入栈的一个值。 (These characters are also documented in the declaration of the structure lua_Debug, between parentheses in the comments following each field.)

如果 what 中有无效选项,该函数返回 0 作为信号; 即便如此,有效的选项仍会被正确处理。


lua_getlocal

[-0, +(0|1), –]

const char *lua_getlocal (lua_State *L, const lua_Debug *ar, int n);

获取关于某个给定活动记录或给定函数的局部变量或临时值的信息。

第一种情况下, 参数 ar 必须是一个由先前对 lua_getstack 的调用 填充的、有效的活动记录, 或是作为 hook 的参数给出的(见 lua_Hook)。 索引 n 选择要检查的局部变量; see debug.getlocal for details about variable indices and names.

lua_getlocal 把变量的值压入栈并返回其名字。

第二种情况下,ar 必须为 NULL, 且要检查的函数必须在栈顶。 这种情况下,只有 Lua 函数的参数可见 (因为没有关于哪些变量处于活跃状态的信息), 且不向栈压入任何值。

当索引大于活动局部变量的数量时, 返回 NULL(且不压入任何东西)。


lua_getstack

[-0, +0, –]

int lua_getstack (lua_State *L, int level, lua_Debug *ar);

获取关于解释器运行时栈的信息。

这个函数用在某给定层级上执行函数的 活动记录(activation record) 标识 填充 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);

获取关于索引 funcindex 处闭包的第 n 个 upvalue 的信息。 它把 upvalue 的值压入栈并返回其名字。 当索引 n 大于 upvalue 数量时, 返回 NULL(且不压入任何东西)。

关于 upvalue 的更多信息,见 debug.getupvalue


lua_Hook

typedef void (*lua_Hook) (lua_State *L, lua_Debug *ar);

调试 hook 函数的类型。

每当 hook 被调用时,它的 ar 参数的 event 字段 被设为触发该 hook 的特定事件。 Lua 用以下常量标识这些事件: 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.

对于调用事件,event 可以是正常的 LUA_HOOKCALL, 或尾调用时的 LUA_HOOKTAILCALL; in this case, there will be no corresponding return event.

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.

Hook functions cannot have continuations, that is, they cannot call lua_yieldk, lua_pcallk, or lua_callk with a non-null k.

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


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:

Hooks are disabled by setting mask to zero.


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.

参数 ar and n are as in the function lua_getlocal, except that ar cannot be NULL, as lua_setlocal only operates on activation records.


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.

参数 funcindex and n are as in the function 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.

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.

参数 funcindex and n are as in the function lua_getupvalue, but n cannot be greater than the number of upvalues.


lua_upvaluejoin

[-0, +0, –]

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.

5 – The Auxiliary Library

The auxiliary library provides several convenient functions to interface C with Lua. While the basic API provides the primitive functions for all interactions between C and Lua, the auxiliary library provides higher-level functions for some common tasks.

All functions and types from the auxiliary library are defined in the header file lauxlib.h and have a prefix luaL_.

All functions in the auxiliary library are built on top of the basic API, and so they provide nothing that cannot be done with that API. Nevertheless, the use of the auxiliary library ensures more consistency to your code.

Several functions in the auxiliary library use internally some extra stack slots. When a function in the auxiliary library uses less than five slots, it does not check the stack size; it simply assumes that there are enough slots.

Several functions in the auxiliary library are used to check C function arguments. Because the error message is formatted for arguments (e.g., "bad argument #1"), you should not use these functions for other stack values.

Functions called luaL_check* always raise an error if the check is not satisfied.

5.1 – Functions and Types

Here we list all functions and types from the auxiliary library in alphabetical order.


luaL_addchar

[-?, +?, m]

void luaL_addchar (luaL_Buffer *B, char c);

Adds the byte c to the buffer B (see luaL_Buffer).


luaL_addgsub

[-?, +?, m]

const void luaL_addgsub (luaL_Buffer *B, const char *s,
                         const char *p, const char *r);

Adds a copy of the string s to the buffer B (see luaL_Buffer), replacing any occurrence of the string p with the string r.


luaL_addlstring

[-?, +?, m]

void luaL_addlstring (luaL_Buffer *B, const char *s, size_t l);

Adds the string pointed to by s with length l to the buffer B (see luaL_Buffer). The string can contain embedded zeros.


luaL_addsize

[-?, +?, –]

void luaL_addsize (luaL_Buffer *B, size_t n);

Adds to the buffer B a string of length n previously copied to the buffer area (see luaL_prepbuffer).


luaL_addstring

[-?, +?, m]

void luaL_addstring (luaL_Buffer *B, const char *s);

Adds the zero-terminated string pointed to by s to the buffer B (see luaL_Buffer).


luaL_addvalue

[-?, +?, m]

void luaL_addvalue (luaL_Buffer *B);

Adds the value on the top of the stack to the buffer B (see luaL_Buffer). Pops the value.

This is the only function on string buffers that can (and must) be called with an extra element on the stack, which is the value to be added to the buffer.


luaL_argcheck

[-0, +0, v]

void luaL_argcheck (lua_State *L,
                    int cond,
                    int arg,
                    const char *extramsg);

Checks whether cond is true. If it is not, raises an error with a standard message (see luaL_argerror).


luaL_argerror

[-0, +0, v]

int luaL_argerror (lua_State *L, int arg, const char *extramsg);

Raises an error reporting a problem with argument arg of the C function that called it, using a standard message that includes extramsg as a comment:

     bad argument #arg to 'funcname' (extramsg)

This function never returns.


luaL_argexpected

[-0, +0, v]

void luaL_argexpected (lua_State *L,
                       int cond,
                       int arg,
                       const char *tname);

Checks whether cond is true. If it is not, raises an error about the type of the argument arg with a standard message (see luaL_typeerror).


luaL_Buffer

typedef struct luaL_Buffer luaL_Buffer;

Type for a string buffer.

A string buffer allows C code to build Lua strings piecemeal. Its pattern of use is as follows:

If you know beforehand the maximum size of the resulting string, you can use the buffer like this:

During its normal operation, a string buffer uses a variable number of stack slots. So, while using a buffer, you cannot assume that you know where the top of the stack is. You can use the stack between successive calls to buffer operations as long as that use is balanced; that is, when you call a buffer operation, the stack is at the same level it was immediately after the previous buffer operation. (The only exception to this rule is luaL_addvalue.) After calling luaL_pushresult, the stack is back to its level when the buffer was initialized, plus the final string on its top.


luaL_buffaddr

[-0, +0, –]

char *luaL_buffaddr (luaL_Buffer *B);

Returns the address of the current content of buffer B (see luaL_Buffer). Note that any addition to the buffer may invalidate this address.


luaL_buffinit

[-0, +?, –]

void luaL_buffinit (lua_State *L, luaL_Buffer *B);

Initializes a buffer B (see luaL_Buffer). This function does not allocate any space; the buffer must be declared as a variable.


luaL_bufflen

[-0, +0, –]

size_t luaL_bufflen (luaL_Buffer *B);

Returns the length of the current content of buffer B (see luaL_Buffer).


luaL_buffinitsize

[-?, +?, m]

char *luaL_buffinitsize (lua_State *L, luaL_Buffer *B, size_t sz);

Equivalent to the sequence luaL_buffinit, luaL_prepbuffsize.


luaL_buffsub

[-?, +?, –]

void luaL_buffsub (luaL_Buffer *B, int n);

Removes n bytes from the buffer B (see luaL_Buffer). The buffer must have at least that many bytes.


luaL_callmeta

[-0, +(0|1), e]

int luaL_callmeta (lua_State *L, int obj, const char *e);

Calls a metamethod.

If the object at index obj has a metatable and this metatable has a field e, this function calls this field passing the object as its only argument. In this case this function returns true and pushes onto the stack the value returned by the call. If there is no metatable or no metamethod, this function returns false without pushing any value on the stack.


luaL_checkany

[-0, +0, v]

void luaL_checkany (lua_State *L, int arg);

Checks whether the function has an argument of any type (including nil) at position arg.


luaL_checkinteger

[-0, +0, v]

lua_Integer luaL_checkinteger (lua_State *L, int arg);

Checks whether the function argument arg is an integer (or can be converted to an integer) and returns this integer.


luaL_checklstring

[-0, +0, v]

const char *luaL_checklstring (lua_State *L, int arg, size_t *l);

Checks whether the function argument arg is a string and returns this string; if l is not NULL fills its referent with the string's length.

This function uses lua_tolstring to get its result, so all conversions and caveats of that function apply here.


luaL_checknumber

[-0, +0, v]

lua_Number luaL_checknumber (lua_State *L, int arg);

Checks whether the function argument arg is a number and returns this number converted to a lua_Number.


luaL_checkoption

[-0, +0, v]

int luaL_checkoption (lua_State *L,
                      int arg,
                      const char *def,
                      const char *const lst[]);

Checks whether the function argument arg is a string and searches for this string in the array lst (which must be NULL-terminated). Returns the index in the array where the string was found. Raises an error if the argument is not a string or if the string cannot be found.

If def is not NULL, the function uses def as a default value when there is no argument arg or when this argument is nil.

This is a useful function for mapping strings to C enums. (The usual convention in Lua libraries is to use strings instead of numbers to select options.)


luaL_checkstack

[-0, +0, v]

void luaL_checkstack (lua_State *L, int sz, const char *msg);

Grows the stack size to top + sz elements, raising an error if the stack cannot grow to that size. msg is an additional text to go into the error message (or NULL for no additional text).


luaL_checkstring

[-0, +0, v]

const char *luaL_checkstring (lua_State *L, int arg);

Checks whether the function argument arg is a string and returns this string.

This function uses lua_tolstring to get its result, so all conversions and caveats of that function apply here.


luaL_checktype

[-0, +0, v]

void luaL_checktype (lua_State *L, int arg, int t);

Checks whether the function argument arg has type t. See lua_type for the encoding of types for t.


luaL_checkudata

[-0, +0, v]

void *luaL_checkudata (lua_State *L, int arg, const char *tname);

Checks whether the function argument arg is a userdata of the type tname (see luaL_newmetatable) and returns the userdata's memory-block address (see lua_touserdata).


luaL_checkversion

[-0, +0, v]

void luaL_checkversion (lua_State *L);

Checks whether the code making the call and the Lua library being called are using the same version of Lua and the same numeric types.


luaL_dofile

[-0, +?, m]

int luaL_dofile (lua_State *L, const char *filename);

Loads and runs the given file. It is defined as the following macro:

     (luaL_loadfile(L, filename) || lua_pcall(L, 0, LUA_MULTRET, 0))

It returns 0 (LUA_OK) if there are no errors, or 1 in case of errors. (Except for out-of-memory errors, which are raised.)


luaL_dostring

[-0, +?, –]

int luaL_dostring (lua_State *L, const char *str);

Loads and runs the given string. It is defined as the following macro:

     (luaL_loadstring(L, str) || lua_pcall(L, 0, LUA_MULTRET, 0))

It returns 0 (LUA_OK) if there are no errors, or 1 in case of errors.


luaL_error

[-0, +0, v]

int luaL_error (lua_State *L, const char *fmt, ...);

Raises an error. The error message format is given by fmt plus any extra arguments, following the same rules of lua_pushfstring. It also adds at the beginning of the message the file name and the line number where the error occurred, if this information is available.

This function never returns, but it is an idiom to use it in C functions as return luaL_error(args).


luaL_execresult

[-0, +3, m]

int luaL_execresult (lua_State *L, int stat);

This function produces the return values for process-related functions in the standard library (os.execute and io.close).


luaL_fileresult

[-0, +(1|3), m]

int luaL_fileresult (lua_State *L, int stat, const char *fname);

This function produces the return values for file-related functions in the standard library (io.open, os.rename, file:seek, etc.).


luaL_getmetafield

[-0, +(0|1), m]

int luaL_getmetafield (lua_State *L, int obj, const char *e);

Pushes onto the stack the field e from the metatable of the object at index obj and returns the type of the pushed value. If the object does not have a metatable, or if the metatable does not have this field, pushes nothing and returns LUA_TNIL.


luaL_getmetatable

[-0, +1, m]

int luaL_getmetatable (lua_State *L, const char *tname);

Pushes onto the stack the metatable associated with the name tname in the registry (see luaL_newmetatable), or nil if there is no metatable associated with that name. 返回被压入值的类型。


luaL_getsubtable

[-0, +1, e]

int luaL_getsubtable (lua_State *L, int idx, const char *fname);

Ensures that the value t[fname], where t is the value at index idx, is a table, and pushes that table onto the stack. Returns true if it finds a previous table there and false if it creates a new table.


luaL_gsub

[-0, +1, m]

const char *luaL_gsub (lua_State *L,
                       const char *s,
                       const char *p,
                       const char *r);

Creates a copy of string s, replacing any occurrence of the string p with the string r. Pushes the resulting string on the stack and returns it.


luaL_len

[-0, +0, e]

lua_Integer luaL_len (lua_State *L, int index);

Returns the "length" of the value at the given index as a number; it is equivalent to the '#' operator in Lua (see §3.4.7). Raises an error if the result of the operation is not an integer. (This case can only happen through metamethods.)


luaL_loadbuffer

[-0, +1, –]

int luaL_loadbuffer (lua_State *L,
                     const char *buff,
                     size_t sz,
                     const char *name);

Equivalent to luaL_loadbufferx with mode equal to NULL.


luaL_loadbufferx

[-0, +1, –]

int luaL_loadbufferx (lua_State *L,
                      const char *buff,
                      size_t sz,
                      const char *name,
                      const char *mode);

Loads a buffer as a Lua chunk. This function uses lua_load to load the chunk in the buffer pointed to by buff with size sz.

This function returns the same results as lua_load. name is the chunk name, used for debug information and error messages. The string mode works as in the function lua_load. In particular, this function supports mode 'B' for fixed buffers.


luaL_loadfile

[-0, +1, m]

int luaL_loadfile (lua_State *L, const char *filename);

Equivalent to luaL_loadfilex with mode equal to NULL.


luaL_loadfilex

[-0, +1, m]

int luaL_loadfilex (lua_State *L, const char *filename,
                                            const char *mode);

Loads a file as a Lua chunk. This function uses lua_load to load the chunk in the file named filename. If filename is NULL, then it loads from the standard input. The first line in the file is ignored if it starts with a #.

The string mode works as in the function lua_load.

This function returns the same results as lua_load, or LUA_ERRFILE for file-related errors.

As lua_load, this function only loads the chunk; it does not run it.


luaL_loadstring

[-0, +1, –]

int luaL_loadstring (lua_State *L, const char *s);

Loads a string as a Lua chunk. This function uses lua_load to load the chunk in the zero-terminated string s.

This function returns the same results as lua_load.

Also as lua_load, this function only loads the chunk; it does not run it.


luaL_makeseed

[-0, +0, –]

unsigned int luaL_makeseed (lua_State *L);

Returns a value with a weak attempt for randomness. The parameter L can be NULL if there is no Lua state available.


luaL_newlib

[-0, +1, m]

void luaL_newlib (lua_State *L, const luaL_Reg l[]);

Creates a new table and registers there the functions in the list l.

It is implemented as the following macro:

     (luaL_newlibtable(L,l), luaL_setfuncs(L,l,0))

The array l must be the actual array, not a pointer to it.


luaL_newlibtable

[-0, +1, m]

void luaL_newlibtable (lua_State *L, const luaL_Reg l[]);

Creates a new table with a size optimized to store all entries in the array l (but does not actually store them). It is intended to be used in conjunction with luaL_setfuncs (see luaL_newlib).

It is implemented as a macro. The array l must be the actual array, not a pointer to it.


luaL_newmetatable

[-0, +1, m]

int luaL_newmetatable (lua_State *L, const char *tname);

If the registry already has the key tname, returns 0. Otherwise, creates a new table to be used as a metatable for userdata, adds to this new table the pair __name = tname, adds to the registry the pair [tname] = new table, and returns 1.

In both cases, the function pushes onto the stack the final value associated with tname in the registry.

Usage note: Beware the use of the return value of this function to conditionally initializes the new metatable (e.g., by adding metamethods to it). If the initialization raises an error, the metatable will not be properly initialized, but a subsequent execution of that code will detect that the metatable already exists and then skip the initialization.


luaL_newstate

[-0, +0, –]

lua_State *luaL_newstate (void);

Creates a new Lua state. It calls lua_newstate with luaL_alloc as the allocator function and the result of luaL_makeseed(NULL) as the seed, and then sets a warning function and a panic function (see §4.4) that print messages to the standard error output.

Returns the new state, or NULL if there is a memory allocation error.


luaL_opt

[-0, +0, –]

T luaL_opt (L, func, arg, dflt);

This macro is defined as follows:

     (lua_isnoneornil(L,(arg)) ? (dflt) : func(L,(arg)))

In words, if the argument arg is nil or absent, the macro results in the default dflt. Otherwise, it results in the result of calling func with the state L and the argument index arg as arguments. Note that it evaluates the expression dflt only if needed.


luaL_optinteger

[-0, +0, v]

lua_Integer luaL_optinteger (lua_State *L,
                             int arg,
                             lua_Integer d);

If the function argument arg is an integer (or it is convertible to an integer), returns this integer. If this argument is absent or is nil, returns d. Otherwise, raises an error.


luaL_optlstring

[-0, +0, v]

const char *luaL_optlstring (lua_State *L,
                             int arg,
                             const char *d,
                             size_t *l);

If the function argument arg is a string, returns this string. If this argument is absent or is nil, returns d. Otherwise, raises an error.

If l is not NULL, fills its referent with the result's length. If the result is NULL (only possible when returning d and d == NULL), its length is considered zero.

This function uses lua_tolstring to get its result, so all conversions and caveats of that function apply here.


luaL_optnumber

[-0, +0, v]

lua_Number luaL_optnumber (lua_State *L, int arg, lua_Number d);

If the function argument arg is a number, returns this number as a lua_Number. If this argument is absent or is nil, returns d. Otherwise, raises an error.


luaL_optstring

[-0, +0, v]

const char *luaL_optstring (lua_State *L,
                            int arg,
                            const char *d);

If the function argument arg is a string, returns this string. If this argument is absent or is nil, returns d. Otherwise, raises an error.


luaL_prepbuffer

[-?, +?, m]

char *luaL_prepbuffer (luaL_Buffer *B);

Equivalent to luaL_prepbuffsize with the predefined size LUAL_BUFFERSIZE.


luaL_prepbuffsize

[-?, +?, m]

char *luaL_prepbuffsize (luaL_Buffer *B, size_t sz);

Returns an address to a space of size sz where you can copy a string to be added to buffer B (see luaL_Buffer). After copying the string into this space you must call luaL_addsize with the size of the string to actually add it to the buffer.


luaL_pushfail

[-0, +1, –]

void luaL_pushfail (lua_State *L);

Pushes the fail value onto the stack (see §6).


luaL_pushresult

[-?, +1, m]

void luaL_pushresult (luaL_Buffer *B);

Finishes the use of buffer B leaving the final string on the top of the stack.


luaL_pushresultsize

[-?, +1, m]

void luaL_pushresultsize (luaL_Buffer *B, size_t sz);

Equivalent to the sequence luaL_addsize, luaL_pushresult.


luaL_ref

[-1, +0, m]

int luaL_ref (lua_State *L, int t);

Creates and returns a reference, in the table at index t, for the object on the top of the stack (and pops the object).

The reference system uses the integer keys of the table. A reference is a unique integer key; luaL_ref ensures the uniqueness of the keys it returns. The entry 1 is reserved for internal use. Before the first use of luaL_ref, the integer keys of the table should form a proper sequence (no holes), and the value at entry 1 should be false: nil if the sequence is empty, false otherwise. You should not manually set integer keys in the table after the first use of luaL_ref.

You can retrieve an object referred by the reference r by calling lua_rawgeti(L,t,r) or lua_geti(L,t,r). The function luaL_unref frees a reference.

If the object on the top of the stack is nil, luaL_ref returns the constant LUA_REFNIL. The constant LUA_NOREF is guaranteed to be different from any reference returned by luaL_ref.


luaL_Reg

typedef struct luaL_Reg {
  const char *name;
  lua_CFunction func;
} luaL_Reg;

Type for arrays of functions to be registered by luaL_setfuncs. name is the function name and func is a pointer to the function. Any array of luaL_Reg must end with a sentinel entry in which both name and func are NULL.


luaL_requiref

[-0, +1, e]

void luaL_requiref (lua_State *L, const char *modname,
                    lua_CFunction openf, int glb);

If package.loaded[modname] is not true, calls the function openf with the string modname as an argument and sets the call result to package.loaded[modname], as if that function has been called through require.

If glb is true, also stores the module into the global variable modname.

Leaves a copy of the module on the stack.


luaL_setfuncs

[-nup, +0, m]

void luaL_setfuncs (lua_State *L, const luaL_Reg *l, int nup);

Registers all functions in the array l (see luaL_Reg) into the table on the top of the stack (below optional upvalues, see next).

When nup is not zero, all functions are created with nup upvalues, initialized with copies of the nup values previously pushed on the stack on top of the library table. These values are popped from the stack after the registration.

A function with a NULL value represents a placeholder, which is filled with false.


luaL_setmetatable

[-0, +0, –]

void luaL_setmetatable (lua_State *L, const char *tname);

Sets the metatable of the object on the top of the stack as the metatable associated with name tname in the registry (see luaL_newmetatable).


luaL_alloc

void *luaL_alloc (void *ud, void *ptr, size_t osize, size_t nsize);

A standard allocator function for Lua (see lua_Alloc), built on top of the C functions realloc and free.


luaL_Stream

typedef struct luaL_Stream {
  FILE *f;
  lua_CFunction closef;
} luaL_Stream;

The standard representation for file handles used by the standard I/O library.

A file handle is implemented as a full userdata, with a metatable called LUA_FILEHANDLE (where LUA_FILEHANDLE is a macro with the actual metatable's name). The metatable is created by the I/O library (see luaL_newmetatable).

This userdata must start with the structure luaL_Stream; it can contain other data after this initial structure. The field f points to the corresponding C stream, or it is NULL to indicate an incompletely created handle. The field closef points to a Lua function that will be called to close the stream when the handle is closed or collected; this function receives the file handle as its sole argument and must return either a true value, in case of success, or a false value plus an error message, in case of error. Once Lua calls this field, it changes the field value to NULL to signal that the handle is closed.


luaL_testudata

[-0, +0, m]

void *luaL_testudata (lua_State *L, int arg, const char *tname);

This function works like luaL_checkudata, except that, when the test fails, it returns NULL instead of raising an error.


luaL_tolstring

[-0, +1, e]

const char *luaL_tolstring (lua_State *L, int idx, size_t *len);

Converts any Lua value at the given index to a C string in a reasonable format. The resulting string is pushed onto the stack and also returned by the function (see §4.1.3). If len is not NULL, the function also sets *len with the string length.

If the value has a metatable with a __tostring field, then luaL_tolstring calls the corresponding metamethod with the value as argument, and uses the result of the call as its result.


luaL_traceback

[-0, +1, m]

void luaL_traceback (lua_State *L, lua_State *L1, const char *msg,
                     int level);

Creates and pushes a traceback of the stack L1. If msg is not NULL, it is appended at the beginning of the traceback. The level parameter tells at which level to start the traceback.


luaL_typeerror

[-0, +0, v]

int luaL_typeerror (lua_State *L, int arg, const char *tname);

Raises a type error for the argument arg of the C function that called it, using a standard message; tname is a "name" for the expected type. This function never returns.


luaL_typename

[-0, +0, –]

const char *luaL_typename (lua_State *L, int index);

Returns the name of the type of the value at the given index.


luaL_unref

[-0, +0, –]

void luaL_unref (lua_State *L, int t, int ref);

Releases a reference (see luaL_ref). The integer ref must be either LUA_NOREF, LUA_REFNIL, or a reference previously returned by luaL_ref and not already released. If ref is either LUA_NOREF or LUA_REFNIL this function does nothing. Otherwise, the entry is removed from the table, so that the referred object can be collected and the reference ref can be used again by luaL_ref.


luaL_where

[-0, +1, m]

void luaL_where (lua_State *L, int lvl);

Pushes onto the stack a string identifying the current position of the control at level lvl in the call stack. Typically this string has the following format:

     chunkname:currentline:

Level 0 is the running function, level 1 is the function that called the running function, etc.

This function is used to build a prefix for error messages.

6 – The Standard Libraries

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

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

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

Currently, Lua has the following standard libraries:

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

6.1 – Loading the Libraries in C code

A C host program must explicitly load the standard libraries into a state, if it wants its scripts to use them. For that, the host program can call the function luaL_openlibs. Alternatively, the host can select which libraries to open, by using luaL_openselectedlibs. Both functions are declared in the header file lualib.h.

The stand-alone interpreter lua (see §7) already opens all standard libraries.


luaL_openlibs

[-0, +0, e]

void luaL_openlibs (lua_State *L);

Opens all standard Lua libraries into the given state.


luaL_openselectedlibs

[-0, +0, e]

void luaL_openselectedlibs (lua_State *L, int load, int preload);

Opens (loads) and preloads selected standard libraries into the state L. (To preload means to add the library loader into the table package.preload, so that the library can be required later by the program. Keep in mind that require itself is provided by the package library. If a program does not load that library, it will be unable to require anything.)

The integer load selects which libraries to load; the integer preload selects which to preload, among those not loaded. Both are masks formed by a bitwise OR of the following constants:

6.2 – Basic Functions

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


assert (v [, message])

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


collectgarbage ([opt [, arg]])

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

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

This function should not be called by a finalizer.


dofile ([filename])

Opens the named file and executes its content as a Lua chunk, returning all values returned by the chunk. When called without arguments, dofile executes the content of the standard input (stdin). In case of errors, dofile propagates the error to its caller. (That is, dofile does not run in protected mode.)


error (message [, level])

Raises an error (see §2.3) with message as the error object. This function never returns.

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


_G

A global variable (not a function) that holds the global environment (see §2.2). Lua itself does not use this variable; changing its value does not affect any environment, nor vice versa.


getmetatable (object)

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


ipairs (t)

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

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

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


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

Loads a chunk.

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

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

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

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

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

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

Lua does not check the consistency of binary chunks. Maliciously crafted binary chunks can crash the interpreter. You can use the mode parameter to prevent loading binary chunks.


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

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


next (table [, index])

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

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

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


pairs (t)

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

Otherwise, returns the next function, the table t, plus two nil values, so that the construction

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

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

See function next for more details about the traversal.


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

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


print (···)

Receives any number of arguments and prints their values to stdout, converting each argument to a string following the same rules of tostring.

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


rawequal (v1, v2)

Checks whether v1 is equal to v2, without invoking the __eq metamethod. Returns a boolean.


rawget (table, index)

Gets the real value of table[index], without using the __index metavalue. table must be a table; index may be any value.


rawlen (v)

Returns the length of the object v, which must be a table or a string, without invoking the __len metamethod. Returns an integer.


rawset (table, index, value)

Sets the real value of table[index] to value, without using the __newindex metavalue. table must be a table, index any value different from nil and NaN, and value any Lua value.

This function returns table.


select (index, ···)

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


setmetatable (table, metatable)

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

This function returns table.

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


tonumber (e [, base])

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

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

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


tostring (v)

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

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

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


type (v)

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


_VERSION

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


warn (msg1, ···)

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

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


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

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

6.3 – Coroutine Manipulation

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


coroutine.close ([co])

Closes coroutine co, that is, closes all its pending to-be-closed variables and puts the coroutine in a dead state. The default for co is the running coroutine.

The given coroutine must be dead, suspended, or be the running coroutine. For the running coroutine, this function does not return. Instead, the resume that (re)started the coroutine returns.

For other coroutines, in case of error (either the original error that stopped the coroutine or errors in closing methods), this function returns false plus the error object; otherwise it returns true.


coroutine.create (f)

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


coroutine.isyieldable ([co])

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

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


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

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

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


coroutine.running ()

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


coroutine.status (co)

Returns the status of the coroutine co, as a string: "running", if the coroutine is running (that is, it is the one that called status); "suspended", if the coroutine is suspended in a call to yield, or if it has not started running yet; "normal" if the coroutine is active but not running (that is, it has resumed another coroutine); and "dead" if the coroutine has finished its body function, or if it has stopped with an error.


coroutine.wrap (f)

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


coroutine.yield (···)

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

6.4 – Modules

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


require (modname)

Loads the given module. The function starts by looking into the package.loaded table to determine whether modname is already loaded. If it is, then require returns the value stored at package.loaded[modname]. (The absence of a second result in this case signals that this call did not have to load the module.) Otherwise, it tries to find a loader for the module.

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

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

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

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


package.config

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


package.cpath

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

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


package.loaded

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

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


package.loadlib (libname, funcname)

Dynamically links the host program with the C library libname.

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

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

This functionality is not supported by ISO C. As such, loadlib is only available on some platforms: Linux, Windows, Mac OS X, Solaris, BSD, plus other Unix systems that support the dlfcn standard.

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


package.path

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

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


package.preload

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

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


package.searchers

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

Each entry in this table is a searcher function. When looking for a module, require calls each of these searchers in ascending order, with the module name (the argument given to require) as its sole argument. If the searcher finds the module, it returns another function, the module loader, plus an extra value, a loader data, that will be passed to that loader and returned as a second result by require. If it cannot find the module, it returns a string explaining why (or nil if it has nothing to say).

Lua initializes this table with four searcher functions.

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

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

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

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

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

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

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

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


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

Searches for the given name in the given path.

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

For instance, if the path is the string

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

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

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

6.5 – String Manipulation

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

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

The string library assumes one-byte character encodings.


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

Returns the internal numeric codes of the characters s[i], s[i+1], ..., s[j]. The default value for i is 1; the default value for j is i. These indices are corrected following the same rules of function string.sub.

Numeric codes are not necessarily portable across platforms.


string.char (···)

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

Numeric codes are not necessarily portable across platforms.


string.dump (function [, strip])

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

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


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

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

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


string.format (formatstring, ···)

Returns a formatted version of its variable number of arguments following the description given in its first argument, which must be a string. The format string follows the same rules as the ISO C function sprintf. The accepted conversion specifiers are A, a, c, d, E, e, f, G, g, i, o, p, s, u, X, x, and '%', plus a non-C specifier q. The accepted flags are '-', '+', '#', '0', and ' ' (space). Both width and precision, when present, are limited to two digits.

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

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

may produce the string:

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

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

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

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

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


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

Returns an iterator function that, each time it is called, returns the next captures from pattern (see §6.5.1) over the string s. If pattern specifies no captures, then the whole match is produced in each call. A third, optional numeric argument init specifies where to start the search; its default value is 1 and can be negative.

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

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

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

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

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


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

Returns a copy of s in which all (or the first n, if given) occurrences of the pattern (see §6.5.1) have been replaced by a replacement string specified by repl, which can be a string, a table, or a function. gsub also returns, as its second value, the total number of matches that occurred. The name gsub comes from Global SUBstitution.

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

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

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

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

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

Here are some examples:

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


string.len (s)

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


string.lower (s)

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


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

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


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

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


string.packsize (fmt)

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


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

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

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


string.reverse (s)

Returns a string that is the string s reversed.


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

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

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


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

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


string.upper (s)

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

6.5.1 – Patterns

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

Character Class:

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

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

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

Pattern Item:

A pattern item can be

Pattern:

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

Captures:

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

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

Multiple matches:

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

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

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

6.5.2 – Format Strings for Pack and Unpack

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

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

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

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

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

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

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

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

6.6 – UTF-8 Support

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

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

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

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


utf8.char (···)

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


utf8.charpattern

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


utf8.codes (s [, lax])

Returns values so that the construction

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

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


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

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


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

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


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

Returns the position of the n-th character of s (counting from byte position i) as two integers: The index (in bytes) where its encoding starts and the index (in bytes) where it ends.

If the specified character is right after the end of s, the function behaves as if there was a '\0' there. If the specified character is neither in the subject nor right after its end, the function returns fail.

A negative n gets characters before position i. The default for i is 1 when n is non-negative and #s + 1 otherwise, so that utf8.offset(s,-n) gets the offset of the n-th character from the end of the string.

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

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

6.7 – Table Manipulation

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

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


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

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


table.create (nseq [, nrec])

Creates a new empty table, preallocating memory. This preallocation may help performance and save memory when you know in advance how many elements the table will have.

Parameter nseq is a hint for how many elements the table will have as a sequence. Optional parameter nrec is a hint for how many other elements the table will have; its default is zero.


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

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


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

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

Returns the destination table a2.


table.pack (···)

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


table.remove (list [, pos])

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

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


table.sort (list [, comp])

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

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

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


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

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

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

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

6.8 – Mathematical Functions

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


math.abs (x)

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


math.acos (x)

Returns the arc cosine of x (in radians).


math.asin (x)

Returns the arc sine of x (in radians).


math.atan (y [, x])

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

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


math.ceil (x)

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


math.cos (x)

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


math.deg (x)

Converts the angle x from radians to degrees.


math.exp (x)

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


math.floor (x)

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


math.fmod (x, y)

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


math.frexp (x)

Returns two numbers m and e such that x = m2e, where e is an integer. When x is zero, NaN, +inf, or -inf, m is equal to x; otherwise, the absolute value of m is in the range [0.5, 1) .


math.huge

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


math.ldexp (m, e)

Returns m2e, where e is an integer.


math.log (x [, base])

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


math.max (x, ···)

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


math.maxinteger

An integer with the maximum value for an integer.


math.min (x, ···)

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


math.mininteger

An integer with the minimum value for an integer.


math.modf (x)

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


math.pi

The value of π.


math.rad (x)

Converts the angle x from degrees to radians.


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

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

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

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


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

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

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

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

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


math.sin (x)

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


math.sqrt (x)

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


math.tan (x)

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


math.tointeger (x)

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


math.type (x)

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


math.ult (m, n)

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

6.9 – Input and Output Facilities

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

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

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

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

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


io.close ([file])

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


io.flush ()

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


io.input ([file])

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

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


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

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

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

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


io.open (filename [, mode])

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

The mode string can be any of the following:

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


io.output ([file])

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


io.popen (prog [, mode])

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

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


io.read (···)

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


io.tmpfile ()

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


io.type (obj)

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


io.write (···)

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


file:close ()

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

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


file:flush ()

Saves any written data to file.


file:lines (···)

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

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

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


file:read (···)

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

The available formats are

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


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

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

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

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


file:setvbuf (mode [, size])

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

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

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


file:write (···)

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

In case of success, this function returns file. Otherwise, it returns four values: fail, the error message, the error code, and the number of bytes it was able to write.

6.10 – Operating System Facilities

This library is implemented through table os.


os.clock ()

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


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

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

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

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

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

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

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


os.difftime (t2, t1)

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


os.execute ([command])

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

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


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

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

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


os.getenv (varname)

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


os.remove (filename)

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


os.rename (oldname, newname)

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


os.setlocale (locale [, category])

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

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

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

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


os.time ([table])

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

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

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

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


os.tmpname ()

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

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

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

6.11 – The Debug Library

This library provides the functionality of the debug interface (§4.7) to Lua programs.

You should exert care when using this library. Several of its functions violate basic assumptions about Lua code (e.g., that variables local to a function cannot be accessed from outside; that userdata metatables cannot be changed by Lua code; that Lua programs do not crash) and therefore can compromise otherwise secure code. Moreover, some functions in this library may be slow. It is good practice to always require this library explicitly before using it.

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


debug.debug ()

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

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


debug.gethook ([thread])

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

Returns fail if there is no active hook.


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

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

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

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


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

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

The first parameter or local variable has index 1, and so on, following the order that they are declared in the code, counting only the variables that are active in the current scope of the function. Compile-time constants may not appear in this listing, if they were optimized away by the compiler. Negative indices refer to vararg arguments; -1 is the first vararg argument. These negative indices are only available when the vararg table has been optimized away; otherwise, the vararg arguments are available in the vararg table.

The function returns fail if there is no variable with the given index, and raises an error when called with a level out of range. (You can call debug.getinfo to check whether the level is valid.)

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

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


debug.getmetatable (value)

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


debug.getregistry ()

Returns the registry table (see §4.3).


debug.getupvalue (f, up)

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

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

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

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


debug.getuservalue (u, n)

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


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

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

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

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

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


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

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

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


debug.setmetatable (value, table)

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


debug.setupvalue (f, up, value)

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

关于 upvalue 的更多信息,见 debug.getupvalue


debug.setuservalue (udata, value, n)

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

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


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

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


debug.upvalueid (f, n)

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

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.


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

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

7 – Lua Standalone

Although Lua has been designed as an extension language, to be embedded in a host C program, it is also frequently used as a standalone language. An interpreter for Lua as a standalone language, called simply lua, is provided with the standard distribution. The standalone interpreter includes all standard libraries. Its usage is:

     lua [options] [script [args]]

The options are:

After handling its options, lua runs the given script. When called without arguments, lua behaves as lua -v -i when the standard input (stdin) is a terminal, and as lua - otherwise.

When called without the option -E, the interpreter checks for an environment variable LUA_INIT_5_5 (or LUA_INIT if the versioned name is not defined) before running any argument. If the variable content has the format @filename, then lua executes the file. Otherwise, lua executes the string itself.

When called with the option -E, Lua does not consult any environment variables. In particular, the values of package.path and package.cpath are set with the default paths defined in luaconf.h. To signal to the libraries that this option is on, the stand-alone interpreter sets the field "LUA_NOENV" in the registry to a true value. Other libraries may consult this field for the same purpose.

The options -e, -l, and -W are handled in the order they appear. For instance, an invocation like

     $ lua -e 'a=1' -llib1 script.lua

will first set a to 1, then require the library lib1, and finally run the file script.lua with no arguments. (Here $ is the shell prompt. Your prompt may be different.)

Before running any code, lua collects all command-line arguments in a global table called arg. The script name goes to index 0, the first argument after the script name goes to index 1, and so on. Any arguments before the script name (that is, the interpreter name plus its options) go to negative indices. For instance, in the call

     $ lua -la b.lua t1 t2

the table is like this:

     arg = { [-2] = "lua", [-1] = "-la",
             [0] = "b.lua",
             [1] = "t1", [2] = "t2" }

If there is no script in the call, the interpreter name goes to index 0, followed by the other arguments. For instance, the call

     $ lua -e "print(arg[1])"

will print "-e". If there is a script, the script is called with arguments arg[1], ···, arg[#arg]. Like all chunks in Lua, the script is compiled as a variadic function.

In interactive mode, Lua repeatedly prompts and waits for a line. After reading a line, Lua first tries to interpret the line as an expression. If it succeeds, it prints its value. Otherwise, it interprets the line as a chunk. If you write an incomplete chunk, the interpreter waits for its completion by issuing a different prompt.

Note that, as each complete line is read as a new chunk, local variables do not outlive lines. To steer clear of confusion, the interpreter gives a warning if a line starts with the reserved word local:

     > x = 20      -- global 'x'
     > local x = 10; print(x)
         --> warning: locals do not survive across lines in interactive mode
         --> 10
     > print(x)     -- back to global 'x'
         --> 20
     > do       -- incomplete chunk
     >> local x = 10; print(x)    -- '>>' prompts for line completion
     >> print(x)
     >> end     -- chunk completed
        --> 10
        --> 10

If the global variable _PROMPT contains a string, then its value is used as the prompt. Similarly, if the global variable _PROMPT2 contains a string, its value is used as the secondary prompt (issued during incomplete statements).

In case of unprotected errors in the script, the interpreter reports the error to the standard error stream. If the error object is not a string but has a metamethod __tostring, the interpreter calls this metamethod to produce the final message. Otherwise, the interpreter converts the error object to a string and adds a stack traceback to it. When warnings are on, they are simply printed in the standard error output.

When finishing normally, the interpreter closes its main Lua state (see lua_close). The script can avoid this step by calling os.exit to terminate.

To allow the use of Lua as a script interpreter in Unix systems, Lua skips the first line of a file chunk if it starts with #. Therefore, Lua scripts can be made into executable programs by using chmod +x and the #! form, as in

     #!/usr/local/bin/lua

Of course, the location of the Lua interpreter may be different in your machine. If lua is in your PATH, then

     #!/usr/bin/env lua

is a more portable solution.

8 – Incompatibilities with the Previous Version

Here we list the incompatibilities that you may find when moving a program from Lua 5.4 to Lua 5.5.

You can avoid some incompatibilities by compiling Lua with appropriate options (see file luaconf.h). However, all these compatibility options will be removed in the future. More often than not, compatibility issues arise when these compatibility options are removed. So, whenever you have the chance, you should try to test your code with a version of Lua compiled with all compatibility options turned off. That will ease transitions to newer versions of Lua.

Lua versions can always change the C API in ways that do not imply source-code changes in a program, such as the numeric values for constants or the implementation of functions as macros. Therefore, you should never assume that binaries are compatible between different Lua versions. Always recompile clients of the Lua API when using a new version.

Similarly, Lua versions can always change the internal representation of precompiled chunks; precompiled chunks are not compatible between different Lua versions.

The standard paths in the official distribution may change between versions.

8.1 – Incompatibilities in the Language

8.2 – Incompatibilities in the Libraries

8.3 – Incompatibilities in the API

9 – The Complete Syntax of Lua

Here is the complete syntax of Lua in extended BNF. As usual in extended BNF, {A} means 0 or more As, and [A] means an optional A. (For operator precedences, see §3.4.8; for a description of the terminals Name, Numeral, and LiteralString, see §3.1.)


	chunk ::= block

	block ::= {stat} [retstat]

	stat ::=  ‘;’ | 
		 varlist ‘=’ explist | 
		 functioncall | 
		 label | 
		 break | 
		 goto Name | 
		 do block end | 
		 while exp do block end | 
		 repeat block until exp | 
		 if exp then block {elseif exp then block} [else block] end | 
		 for Name ‘=’ exp ‘,’ exp [‘,’ exp] do block end | 
		 for namelist in explist do block end | 
		 function funcname funcbody | 
		 local function Name funcbody | 
		 global function Name funcbody | 
		 local attnamelist [‘=’ explist] | 
		 global attnamelist [‘=’ explist] | 
		 global [attrib] ‘*’ 

	attnamelist ::=  [attrib] Name [attrib] {‘,’ Name [attrib]}

	attrib ::= ‘<’ Name ‘>’

	retstat ::= return [explist] [‘;’]

	label ::= ‘::’ Name ‘::’

	funcname ::= Name {‘.’ Name} [‘:’ Name]

	varlist ::= var {‘,’ var}

	var ::=  Name | prefixexp ‘[’ exp ‘]’ | prefixexp ‘.’ Name 

	namelist ::= Name {‘,’ Name}

	explist ::= exp {‘,’ exp}

	exp ::=  nil | false | true | Numeral | LiteralString | ‘...’ | functiondef | 
		 prefixexp | tableconstructor | exp binop exp | unop exp 

	prefixexp ::= var | functioncall | ‘(’ exp ‘)’

	functioncall ::=  prefixexp args | prefixexp ‘:’ Name args 

	args ::=  ‘(’ [explist] ‘)’ | tableconstructor | LiteralString 

	functiondef ::= function funcbody

	funcbody ::= ‘(’ [parlist] ‘)’ block end

	parlist ::= namelist [‘,’ varargparam] | varargparam

	varargparam ::= ‘...’ [Name]

	tableconstructor ::= ‘{’ [fieldlist] ‘}’

	fieldlist ::= field {fieldsep field} [fieldsep]

	field ::= ‘[’ exp ‘]’ ‘=’ exp | Name ‘=’ exp | exp

	fieldsep ::= ‘,’ | ‘;’

	binop ::=  ‘+’ | ‘-’ | ‘*’ | ‘/’ | ‘//’ | ‘^’ | ‘%’ | 
		 ‘&’ | ‘~’ | ‘|’ | ‘>>’ | ‘<<’ | ‘..’ | 
		 ‘<’ | ‘<=’ | ‘>’ | ‘>=’ | ‘==’ | ‘~=’ | 
		 and | or

	unop ::= ‘-’ | not | ‘#’ | ‘~