转载

[译] Lua 5.3 参考手册

Lua 5.3 参考手册

作者 Roberto Ierusalimschy, Luiz Henrique de Figueiredo, Waldemar Celes

译者 云风

Lua.org, PUC-Rio 版权所有 © 2015 , 在遵循 Lua license 条款下,可自由使用。

目录 ·索引 ·中英术语对照表

1 – 概要

Lua 是一门扩展式程序设计语言,它被设计成支持通用过程式编程,并有相关数据描述设施。 同时也很好的支持了面向对象编程、函数式编程、数据驱动式编程。 它作为一个强大、轻量的嵌入式脚本语言,可供任何需要的程序使用。 它以库形式实现,用 clean C 写成。 所谓 Clean C ,指的是标准 C 和 C++ 间共通的一个子集。

作为一个扩展式语言,Lua 没有 "main" 程序的概念: 它只能 嵌入 一个宿主程序中工作, 这个宿主程序被称作 被嵌入的程序 或简称为 宿主 。 宿主程序可以调用函数执行一小段 Lua 代码,可以读写 Lua 变量,可以注入 C 函数让 Lua 代码调用。 依靠这些 C 函数,在各种不同的领域中,都可以将拥有相同句法结构的 Lua 定制为该领域下的编程语言。 Lua 的官方发布版包含了一个叫做 lua 的简单的宿主程序, 它用 Lua 库实现了一个完整的独立 Lua 解释器。 你可以把它作交互式应用或用于批处理。

Lua 是一个自由软件,它的使用许可证决定了它的使用过程没有任何担保。 这份手册中描述的实现,可以在 Lua 的官方网站 www.lua.org 找到。

跟其它的许多参考手册一样,这份文档有些地方比较枯燥。 Lua 设计决定方面的讨论, 可以看看 Lua 网站上提供的技术论文。 有关用 Lua 编程的细节介绍, 可以读一下 Roberto 的书, Programming in Lua

2 – 基本概念

这一章描述了语言的基本概念。

2.1 – 值与类型

Lua 是一门 动态类型语言 。 这意味着变量没有类型;只有值才有类型。 语言中不设类型定义。 所有的值都带有自己的类型。

Lua 中所有的值都是 一等公民 。 这意味着所有的值都可以保存在变量中、 当作参数传递给其它函数、以及作为返回值出现。

Lua 中有八种基本类型: nil , boolean , number , string , function , userdata , thread , and table . Nil 是值 nil 的类型, 它的主要特征就是和其它值区别开; 它通常用来表示一个有意义的值不存在时的状态。 Booleanfalsetrue 两个值的类型。 nilfalse 都会导致条件判断为假; 所有其它的值都表现为真。 Number 代表了整数或实数(浮点数)。 String 表示一个不可变的字节序列。 Lua 是 8 位友好的: 字符串可以包含任意 8 位值, 其中包括零 (' /0 ') 。 Lua 的字符串编码无关; 它不理会字符串里的内容到底是什么。

number 类型有两种内部呈现方式, 一种称为 整数 另一种称为 浮点数 。 对于使用哪种内部形式,Lua 有明确的规则, 但它也按需(参见§3.4.3)自动转换。 因此,程序员需要选择完全忽略其间的差异 还是对如何在内部呈现数字做完全的控制。 标准 Lua 使用 64 位整数以及双精度(64 位)浮点数, 但你可以把 Lua 编译成使用 32 位整数及单精度(32 位)浮点数。 以 32 位表示数字对小型机器以及嵌入式系统特别有意义。 (参见 luaconf.h 文件中的宏 LUA_32BITS 。)

Lua 可以调用(以及操作)用 Lua 或 C (参见§3.4.10)编写的函数。 这两种函数有统一的类型 function

userdata 类型允许将 C 中的数据保存在 Lua 变量中。 用户数据类型的值是一个内存块。 有两种用户数据: 完全用户数据 指一块由 Lua 管理的内存对应的对象; 轻量用户数据 则指一个简单的 C 指针。 用户数据在 Lua 中没有预定义的操作,你只能对它进行赋值操作及判断两个用户数据是否相同。 使用 元表 的话,程序员可以给完全用户数据定义一系列的操作 (参见§2.4)。 在 Lua 代码中,你不能查和修改一个用户数据的值,这些工作只能通过 C API 完成。 这保证了数据仅被宿主程序所控制。

thread 类型表示了一个独立的执行序列,它被用于实现协程 (参见§2.6)。 Lua 线程并非操作系统线程。 Lua 为所有的系统,包括那些不提供原生线程支持的系统,提供了协程支持。

table 是一个关联数组, 也就是说,这个数组不仅仅以数做索引,除了 nil 和 NaN 之外的 Lua 值 都可以做索引。 ( Not a Number 是一个特殊的数字,它用于表示未定义或表示不了的运算结果,比如 0/0 。) 表可以是 异构 的; 也就是说,表内可以包含(除 nil 外的任何类型的值)。 任何键的值若为 nil 就不会被记入表结构内部。 换句话说,对于表内不存在的键,都对应着值 nil

表是 Lua 中唯一的数据结构; 它可被用于表示普通数组、序列、符号表、集合、记录、图、树、等等。 对于记录,Lua 使用域名作为索引。 语言提供了 a.name 这样的语法糖来替代 a["name"] 这种写法以方便记录这种结构的使用。 有多种方式在 Lua 中创建表结构(参见§3.4.9)。

我们使用 序列 这个术语来表示一个用 {1.. n } 的正整数集 做索引的表。这里的非负整数 n 被称为这个序列的长度 (参见§3.4.7)。

和索引一样,表中每个域的值也可以是任何类型。 需要特别指出的是:既然函数是一等公民,那么表的域也可以是函数。 这样,表就可以携带 方法 了。 (参见§3.4.11)。

索引一张表的原则遵循语言中的直接比较规则。 当且仅当 ij 直接比较相等时 (即不通过元方法的比较), 表达式 a[i]a[j] 表示了表中相同的元素。 特别指出:一个可以完全表达为整数的浮点数和对应的整数相等 (例如: 1.0 == 1 )。 为了消除歧义,当一个可以完全表达为整数的浮点数做为键值时, 都会被转换为对应的整数储存。 例如,当你写 a[2.0] = true 时, 实际被插入表中的键是整数 。 (另一方面,2 与 " " 是两个不同的 Lua 值, 故而它们可以是同一张表中的不同项。)

表、函数、线程、以及完全用户数据在 Lua 中被称为 对象 : 变量并不真的 持有 它们的值,而仅保存了对这些对象的 引用 。 赋值、参数传递、函数返回,都是针对引用而不是针对值的操作; 这些操作均不会做任何形式的隐式拷贝。

库函数 type 用于以字符串形式返回给定值的类型。 (参见§6.1)。

2.2 – 环境与全局环境

后面在§3.2以及§3.3.3会讨论, 引用一个叫 var 的自由名字(指在任何层级都未被声明的名字) 在句法上都被翻译为 _ENV.var 。 此外,每个被编译的 Lua 代码块都会有一个额外的局部变量叫 _ENV (参见§3.3.2), 因此, _ENV 这个名字永远都不会成为一个代码块中的自由名字。

在转译那些自由名字时, _ENV 是否是那个额外的局部变量无所谓。 _ENV 和其它你可以使用的变量名没有区别。 这里特别指出,你可以定义一个新变量或指定一个参数叫这个名字。 当编译器在转译自由名字时所用到的 _ENV , 指的是你的程序在那个点上可见的那个名为 _ENV 的变量。 (Lua 的可见性规则参见§3.5)

_ENV 用于值的那张表被称为 环境

Lua 保有一个被称为 全局环境 特别环境。它被保存在 C 注册表 (参见§4.5)的一个特别索引下。 在 Lua 中,全局变量 _G 被初始化为这个值。 ( _G 不被内部任何地方使用。)

当 Lua 加载一个代码块, _ENV 这个上值的默认值就是这个全局环境 (参见 load )。 因此,在默认情况下,Lua 代码中提及的自由名字都指的全局环境中的相关项 (因此,它们也被称为 全局变量 )。 此外,所有的标准库都被加载入全局环境,一些函数也针对这个环境做操作。 你可以用 load (或 loadfile )加载代码块,并赋予它们不同的环境。 (在 C 里,当你加载一个代码块后,可以通过改变它的第一个上值来改变它的环境。)

2.3 – 错误处理

Lua 作为一门嵌入式语言, 所有的 Lua 行为都始于宿主程序的 C 代码中对于 Lua 库里某函数的一次调用。 (当你使用 Lua 独立版本时, lua 程序就是那个宿主程序。) 在编译或运行一个 Lua 代码块时,无论发生任何错误, 控制权都返还给宿主。接下来可以针对情况来采取恰当的措施 (比如打印错误消息)。

Lua 代码中可以通过调用 error 函数来显式的抛出一个错误。 如果你需要在 Lua 中捕获这些错误, 你可以使用 pcallxpcall保护模式 来调用一个函数。

无论何时错误发生,都会产生一个携带有错误信息的 错误对象 (也被称为 错误消息 )。 Lua 本身只会产生字符串类型的错误对象, 但你的程序可以为一个错误抛出任何类型的错误对象。 这就看 Lua 程序或你的宿主如何处理这些错误对象了。

当你使用 xpcalllua_pcall 时, 你应当给出一个 消息处理器 用于发生错误时的处理流程。 这个处理器函数会被传入原始的错误消息,并应返回一个新的错误消息。 它在错误发生后栈尚未展开时调用, 因此它可以通过栈来收集更多的信息。 例如它可以通过探知栈来创建一组栈回溯信息。 这个处理器函数也被保护模式调用以保护; 因此在处理器函数内发生的错误会再次调用它。 如果递归调用太深,Lua 会打破递归并返回一个恰当的消息。

2.4 – 元表及元方法

Lua 中的每个值都可以用一个 元表 。 这个 元表 就是一个普通的 Lua 表, 它用于定义原始值在特定操作下的行为。 如果你想改变一个值在特定操作下的行为,你可以在它的元表中设置对应域。 例如,当你对非数字值做加操作时, Lua 会检查该值的元表中的 " __add " 域下的函数。 如果能找到,Lua 则调用这个函数来完成加这个操作。

元表中的键对应着不同的 事件 名; 键关联的那些值被称为 元方法 。 在上面那个例子中引用的事件为 "add" , 完成加操作的那个函数就是元方法。

你可以用 getmetatable 函数 来获取任何值的元表。

使用 setmetatable 来替换一张表的元表。在 Lua 中,你不可以改变其它类型的值的元表 (除非你使用调试库(参见§6.10)); 若想改变这些非表类型的值的元表,请使用 C API。

表和完全用户数据有独立的元表 (当然,多个表和用户数据可以共享同一个元表)。 其它类型的值按类型共享元表; 也就是说所有的数字都共享同一个元表, 所有的字符串共享另一个元表等等。 默认情况下,值是没有元表的, 但字符串库在初始化的时候为字符串类型设置了元表 (参见§6.4)。

元表决定了一个对象在数学运算、位运算、比较、连接、 取长度、调用、索引时的行为。 元表还可以定义一个函数,当表对象或用户数据对象在垃圾回收 (参见§2.5)时调用它。

接下来会给出一张元表可以控制的事件的完整列表。 每个操作都用对应的事件名来区分。 每个事件的键名用加有 ' __ ' 前缀的字符串来表示; 例如 "add" 操作的键名为字符串 " __add "。 注意、Lua 从元表中直接获取元方法; 访问元表中的元方法永远不会触发另一次元方法。 下面的代码模拟了 Lua 从一个对象 obj 中获取一个元方法的过程:

rawget(getmetatable(obj) or {}, "__" .. event_name)

对于一元操作符(取负、求长度、位反), 元方法调用的时候,第二个参数是个哑元,其值等于第一个参数。 这样处理仅仅是为了简化 Lua 的内部实现 (这样处理可以让所有的操作都和二元操作一致), 这个行为有可能在将来的版本中移除。 (使用这个额外参数的行为都是不确定的。)

  • "add": + 操作。 如果任何不是数字的值(包括不能转换为数字的字符串)做加法, Lua 就会尝试调用元方法。 首先、Lua 检查第一个操作数(即使它是合法的), 如果这个操作数没有为 " __add " 事件定义元方法, Lua 就会接着检查第二个操作数。 一旦 Lua 找到了元方法, 它将把两个操作数作为参数传入元方法, 元方法的结果(调整为单个值)作为这个操作的结果。 如果找不到元方法,将抛出一个操作。
  • "sub": - 操作。 行为和 "add" 操作类似。
  • "mul": * 操作。 行为和 "add" 操作类似。
  • "div": / 操作。 行为和 "add" 操作类似。
  • "mod": % 操作。 行为和 "add" 操作类似。
  • "pow": ^ (次方)操作。 行为和 "add" 操作类似。
  • "unm": - (取负)操作。 行为和 "add" 操作类似。
  • "idiv": // (向下取整除法)操作。 行为和 "add" 操作类似。
  • "band": & (按位与)操作。 行为和 "add" 操作类似, 不同的是 Lua 会在任何一个操作数无法转换为整数时 (参见§3.4.3)尝试取元方法。
  • "bor": | (按位或)操作。 行为和 "band" 操作类似。
  • "bxor": ~ (按位异或)操作。 行为和 "band" 操作类似。
  • "bnot": ~ (按位非)操作。 行为和 "band" 操作类似。
  • "shl": << (左移)操作。 行为和 "band" 操作类似。
  • "shr": >> (右移)操作。 行为和 "band" 操作类似。
  • "concat": .. (连接)操作。 行为和 "add" 操作类似, 不同的是 Lua 在任何操作数即不是一个字符串 也不是数字(数字总能转换为对应的字符串)的情况下尝试元方法。
  • "len": # (取长度)操作。 如果对象不是字符串,Lua 会尝试它的元方法。 如果有元方法,则调用它并将对象以参数形式传入, 而返回值(被调整为单个)则作为结果。 如果对象是一张表且没有元方法, Lua 使用表的取长度操作(参见§3.4.7)。 其它情况,均抛出错误。
  • "eq": == (等于)操作。 和 "add" 操作行为类似, 不同的是 Lua 仅在两个值都是表或都是完全用户数据 且它们不是同一个对象时才尝试元方法。 调用的结果总会被转换为布尔量。
  • "lt": < (小于)操作。 和 "add" 操作行为类似, 不同的是 Lua 仅在两个值不全为整数也不全为字符串时才尝试元方法。 调用的结果总会被转换为布尔量。
  • "le": <= (小于等于)操作。 和其它操作不同, 小于等于操作可能用到两个不同的事件。 首先,像 "lt" 操作的行为那样,Lua 在两个操作数中查找 " __le " 元方法。 如果一个元方法都找不到,就会再次查找 " __lt " 事件, 它会假设 a <= b 等价于 not (b < a) 。 而其它比较操作符类似,其结果会被转换为布尔量。
  • "index": 索引 table[key] 。 当 table 不是表或是表 table 中不存在 key 这个键时,这个事件被触发。 此时,会读出 table 相应的元方法。

    尽管名字取成这样, 这个事件的元方法其实可以是一个函数也可以是一张表。 如果它是一个函数,则以 tablekey 作为参数调用它。 如果它是一张表,最终的结果就是以 key 取索引这张表的结果。 (这个索引过程是走常规的流程,而不是直接索引, 所以这次索引有可能引发另一次元方法。)

  • "newindex": 索引赋值 table[key] = value 。 和索引事件类似,它发生在 table 不是表或是表 table 中不存在 key 这个键的时候。 此时,会读出 table 相应的元方法。

    同索引过程那样, 这个事件的元方法即可以是函数,也可以是一张表。 如果是一个函数, 则以 tablekey 、以及 value 为参数传入。 如果是一张表, Lua 对这张表做索引赋值操作。 (这个索引过程是走常规的流程,而不是直接索引赋值, 所以这次索引赋值有可能引发另一次元方法。)

    一旦有了 "newindex" 元方法, Lua 就不再做最初的赋值操作。 (如果有必要,在元方法内部可以调用 rawset 来做赋值。)

  • "call": 函数调用操作 func(args) 。 当 Lua 尝试调用一个非函数的值的时候会触发这个事件 (即 func 不是一个函数)。 查找 func 的元方法, 如果找得到,就调用这个元方法, func 作为第一个参数传入,原来调用的参数( args )后依次排在后面。

2.5 – 垃圾收集

Lua 采用了自动内存管理。 这意味着你不用操心新创建的对象需要的内存如何分配出来, 也不用考虑在对象不再被使用后怎样释放它们所占用的内存。 Lua 运行了一个 垃圾收集器 来收集所有 死对象 (即在 Lua 中不可能再访问到的对象)来完成自动内存管理的工作。 Lua 中所有用到的内存,如:字符串、表、用户数据、函数、线程、 内部结构等,都服从自动管理。

Lua 实现了一个增量标记-扫描收集器。 它使用这两个数字来控制垃圾收集循环: 垃圾收集器间歇率垃圾收集器步进倍率 。 这两个数字都使用百分数为单位 (例如:值 100 在内部表示 1 )。

垃圾收集器间歇率控制着收集器需要在开启新的循环前要等待多久。 增大这个值会减少收集器的积极性。 当这个值比 100 小的时候,收集器在开启新的循环前不会有等待。 设置这个值为 200 就会让收集器等到总内存使用量达到 之前的两倍时才开始新的循环。

垃圾收集器步进倍率控制着收集器运作速度相对于内存分配速度的倍率。 增大这个值不仅会让收集器更加积极,还会增加每个增量步骤的长度。 不要把这个值设得小于 100 , 那样的话收集器就工作的太慢了以至于永远都不干不完一个循环。 默认值是 200 ,这表示收集器以内存分配的“两倍”速工作。

如果你把步进倍率设为一个非常大的数字 (比你的程序可能用到的字节数还大 10% ), 收集器的行为就像一个 stop-the-world 收集器。 接着你若把间歇率设为 200 , 收集器的行为就和过去的 Lua 版本一样了: 每次 Lua 使用的内存翻倍时,就做一次完整的收集。

你可以通过在 C 中调用 lua_gc 或在 Lua 中调用 collectgarbage 来改变这俩数字。 这两个函数也可以用来直接控制收集器(例如停止它或重启它)。

2.5.1 – 垃圾收集元方法

你可以为表设定垃圾收集的元方法, 对于完全用户数据(参见§2.4), 则需要使用 C API 。 该元方法被称为 终结器 。 终结器允许你配合 Lua 的垃圾收集器做一些额外的资源管理工作 (例如关闭文件、网络或数据库连接,或是释放一些你自己的内存)。

如果要让一个对象(表或用户数据)在收集过程中进入终结流程, 你必须 标记 它需要触发终结器。 当你为一个对象设置元表时,若此刻这张元表中用一个以字符串 " __gc " 为索引的域,那么就标记了这个对象需要触发终结器。 注意:如果你给对象设置了一个没有 __gc 域的元表,之后才给元表加上这个域, 那么这个对象是没有被标记成需要触发终结器的。 然而,一旦对象被标记, 你还是可以自由的改变其元表中的 __gc 域的。

当一个被标记的对象成为了垃圾后, 垃圾收集器并不会立刻回收它。 取而代之的是,Lua 会将其置入一个链表。 在收集完成后,Lua 将遍历这个链表。 Lua 会检查每个链表中的对象的 __gc 元方法:如果是一个函数,那么就以对象为唯一参数调用它; 否则直接忽略它。

在每次垃圾收集循环的最后阶段, 本次循环中检测到的需要被回收之对象, 其终结器的触发次序按当初给对象作需要触发终结器的标记之次序的逆序进行; 这就是说,第一个被调用的终结器是程序中最后一个被标记的对象所携的那个。 每个终结器的运行可能发生在执行常规代码过程中的任意一刻。

由于被回收的对象还需要被终结器使用, 该对象(以及仅能通过它访问到的其它对象)一定会被 Lua 复活 。 通常,复活是短暂的,对象所属内存会在下一个垃圾收集循环释放。 然后,若终结器又将对象保存去一些全局的地方 (例如:放在一个全局变量里),这次复活就持续生效了。 此外,如果在终结器中对一个正进入终结流程的对象再次做一次标记让它触发终结器, 只要这个对象在下个循环中依旧不可达,它的终结函数还会再调用一次。 无论是哪种情况, 对象所属内存仅在垃圾收集循环中该对象不可达且 没有被标记成需要触发终结器才会被释放。

当你关闭一个状态机(参见 lua_close ), Lua 将调用所有被标记了需要触发终结器对象的终结过程, 其次序为标记次序的逆序。 在这个过程中,任何终结器再次标记对象的行为都会不会生效。

2.5.2 – 弱表

弱表 指内部元素为 弱引用 的表。 垃圾收集器会忽略掉弱引用。 换句话说,如果一个对象只被弱引用引用到, 垃圾收集器就会回收这个对象。

一张弱表可以有弱键或是弱值,也可以键值都是弱引用。 仅含有弱键的表允许收集器回收它的键,但会阻止对值所指的对象被回收。 若一张表的键值均为弱引用, 那么收集器可以回收其中的任意键和值。 任何情况下,只要键或值的任意一项被回收, 相关联的键值对都会从表中移除。 一张表的元表中的 __mode 域控制着这张表的弱属性。 当 __mode 域是一个包含字符 ' k ' 的字符串时,这张表的所有键皆为弱引用。 当 __mode 域是一个包含字符 ' v ' 的字符串时,这张表的所有值皆为弱引用。

属性为弱键强值的表也被称为 暂时表 。 对于一张暂时表, 它的值是否可达仅取决于其对应键是否可达。 特别注意,如果表内的一个键仅仅被其值所关联引用, 这个键值对将被表内移除。

对一张表的弱属性的修改仅在下次收集循环才生效。 尤其是当你把表由弱改强,Lua 还是有可能在修改生效前回收表内一些项目。

只有那些有显式构造过程的对象才会被弱表中移除。 值,例如数字和轻量 C 函数,不受垃圾收集器管辖, 因此不会从弱表中移除 (除非它们的关联项被回收)。 虽然字符串受垃圾回收器管辖, 但它们没有显式的构造过程,所以也不会从弱表中移除。

弱表针对复活的对象 (指那些正在走终结流程,仅能被终结器访问的对象) 有着特殊的行为。 弱值引用的对象,在运行它们的终结器前就被移除了, 而弱键引用的对象则要等到终结器运行完毕后,到下次收集当对象真的被释放时才被移除。 这个行为使得终结器运行时得以访问到由该对象在弱表中所关联的属性。

如果一张弱表在当次收集循环内的复活对象中, 那么在下个循环前这张表有可能未被正确地清理。

2.6 – 协程

Lua 支持协程,同时它也被称为 协同式多线程 。 Lua 为每个协程提供一个独立的运行序。 然而和多线程系统中的线程不同, 协程仅在显式地调用一个让出函数时才挂起当前的执行状态。

通过调用 coroutine.create 可创建一个协程。 它唯一的参数是一个函数,这个函数将作为这个协程的主函数。 create 函数仅仅创建出这个协程然后返回它的句柄 (一个类型为 thread 的对象); 它并不运行该协程。

通过调用 coroutine.resume 可执行一个协程。 第一次调用 coroutine.resume 时,第一个参数应传入 coroutine.create 返回的线程对象,这样协程就会从其主函数的第一行开始执行。 coroutine.resume 后面的参数将作为主函数的参数传入。 协程将一直运行到它结束或 让出

协程的运行可能被两种方式终止: 正常途径是主函数返回 (显式返回或运行完最后一条指令); 非正常途径是发生了一个未被捕获的错误。 对于正常结束, coroutine.resume 将返回 true , 并接上协程主函数的返回值。 当错误发生时, coroutine.resume 将返回 false 与错误消息。

让出协程的执行通过调用 coroutine.yield 完成。 当协程让出, 即使让出发生在内嵌函数调用中 (即不在主函数,但在主函数直接或间接调用的函数内部), 之前对该协程调用的 coroutine.resume 会立刻返回。 在让出的情况下, coroutine.resume 依旧返回 true , 接下来的返回值是传给 coroutine.yield 的那些参数。 当下一次你延续同一个协程时, 协程会接在让出点继续运行。 调用 coroutine.yield 的让出点会返回传给 coroutine.resume 的额外参数。

就像 coroutine.create 那样, coroutine.wrap 函数也会创建一个协程。 不同的是,它不返回协程本身,而是返回一个函数。 调用这个函数将延续这个协程。 为这个函数提供的参数相当于 传给 coroutine.resume 的额外参数。 coroutine.wrap 的返回值是 coroutine.resume 的返回值中除去第一个返回值(布尔型的错误码)剩余的部分。 和 coroutine.resume 不同, coroutine.wrap 不会捕获错误; 错误会传播给调用者。

下面的代码展示了一个协程工作的范例:

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_resume , 以及 lua_yield

3 – 语言定义

这一章描述了 Lua 的词法、语法和句法。 换句话说,本章描述哪些符记是有效的, 它们如何被组合起来,这些组合方式有什么含义。

关于语言的构成概念将用常见的扩展 BNF 表达式写出。 也就是这个样子: { a } 表示 0 或多个 a , [ a ] 表示一个可选的 a 。 可以被分解的非最终符号会这样写 non-terminal , 关键字会写成这样 kword , 而其它不能被分解的最终符号则写成这样 ‘ = ’ 。 完整的 Lua 语法可以在本手册最后一章§9找到。

3.1 – 词法约定

Lua 语言的格式自由。 它会忽略语法元素(符记)间的空格(包括换行)和注释, 仅把它们看作为名字和关键字间的分割符。

Lua 中的 名字 (也被称为 标识符 ) 可以是由非数字打头的任意字母下划线和数字构成的字符串。 标识符可用于对变量、表的域、以及标签命名。

下列 关键字 是保留的,不可用于名字:

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

Lua 语言对大小写敏感: and 是一个保留字,但 AndAND 则是两个不同的有效名字。 作为一个约定,程序应避免创建以下划线加一个或多个大写字母构成的名字 (例如 _VERSION )。

下列字符串是另外一些符记:

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

字面串 可以用单引号或双引号括起。 字面串内部可以包含下列 C 风格的转义串: ' /a ' (响铃), ' /b ' (退格), ' /f ' (换页), ' /n ' (换行), ' /r ' (回车), ' /t ' (横项制表), ' /v ' (纵向制表), ' // ' (反斜杠), ' /" ' (双引号), 以及 ' /' ' (单引号)。 在反斜杠后跟一个真正的换行等价于在字符串中写一个换行符。 转义串 ' /z ' 会忽略其后的一系列空白符,包括换行; 它在你需要对一个很长的字符串常量断行为多行并希望在每个新行保持缩进时非常有用。

Lua 中的字符串可以保存任意 8 位值,其中包括用 ' /0 ' 表示的 0 。 一般而言,你可以用字符的数字值来表示这个字符。 方式是用转义串 /xXX , 此处的 XX 必须是恰好两个字符的 16 进制数。 或者你也可以使用转义串 /ddd , 这里的 ddd 是一到三个十进制数字。 (注意,如果在转义符后接着恰巧是一个数字符号的话, 你就必须在这个转义形式中写满三个数字。)

对于用 UTF-8 编码的 Unicode 字符,你可以用 转义符 /u{XXX} 来表示 (这里必须有一对花括号), 此处的 XXX 是用 16 进制表示的字符编号。

字面串还可以用一种 长括号 括起来的方式定义。 我们把两个正的方括号间插入 n 个等号定义为 n 级开长括号 。 就是说,0 级开的长括号写作 [[ , 一级开长括号写作 [=[ , 如此等等。 闭长括号 也作类似定义; 举个例子,4 级反的长括号写作 ]====] 。 一个 长字面串 可以由任何一级的开长括号开始,而由第一个碰到的同级的闭长括号结束。 这种方式描述的字符串可以包含任何东西,当然特定级别的反长括号除外。 整个词法分析过程将不受分行限制,不处理任何转义符,并且忽略掉任何不同级别的长括号。 其中碰到的任何形式的换行串(回车、换行、回车加换行、换行加回车),都会被转换为单个换行符。

字面串中的每个不被上述规则影响的字节都呈现为本身。 然而,Lua 是用文本模式打开源文件解析的, 一些系统的文件操作函数对某些控制字符的处理可能有问题。 因此,对于非文本数据,用引号括起来并显式按转义符规则来表述更安全。

为了方便起见, 当一个开长括号后紧接一个换行符时, 这个换行符不会放在字符串内。 举个例子,假设一个系统使用 ASCII 码 (此时 ' a ' 编码为 97 , 换行编码为 10 ,' ' 编码为 49 ), 下面五种方式描述了完全相同的字符串:

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

数字常量 (或称为 数字量 ) 可以由可选的小数部分和可选的十为底的指数部分构成, 指数部分用字符 ' e ' 或 ' E ' 来标记。 Lua 也接受以 0x0X 开头的 16 进制常量。 16 进制常量也接受小数加指数部分的形式,指数部分是以二为底, 用字符 ' p ' 或 ' P ' 来标记。 数字常量中包含小数点或指数部分时,被认为是一个浮点数; 否则被认为是一个整数。 下面有一些合法的整数常量的例子:

3   345   0xff   0xBEBADA

以下为合法的浮点常量:

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

在字符串外的任何地方出现以双横线 ( -- ) 开头的部分是 注释 。 如果 -- 后没有紧跟着一个开大括号, 该注释为 短注释 , 注释到当前行末截至。 否则,这是一段 长注释 , 注释区一直维持到对应的闭长括号。 长注释通常用于临时屏蔽掉一大段代码。

3.2 – 变量

变量是储存值的地方。 Lua 中有三种变量: 全局变量、局部变量和表的域。

单个名字可以指代一个全局变量也可以指代一个局部变量 (或者是一个函数的形参,这是一种特殊形式的局部变量)。

var ::= Name

名字指§3.1中定义的标识符。

所有没有显式声明为局部变量(参见§3.3.7) 的变量名都被当做全局变量。 局部变量有其 作用范围 : 局部变量可以被定义在它作用范围中的函数自由使用(参见§3.5)。

在变量的首次赋值之前,变量的值均为 nil

方括号被用来对表作索引:

var ::= prefixexp ‘[’ exp ‘]

对全局变量以及表的域之访问的含义可以通过元表来改变。 以索引方式访问一个变量 t[i] 等价于 调用 gettable_event(t,i) 。 (参见§2.4,有一份完整的关于 gettable_event 函数的说明。 这个函数并没有在 lua 中定义出来,也不能在 lua 中调用。这里我们把提到它只是方便说明问题。)

var.Name 这种语法只是一个语法糖,用来表示 var["Name"]

var ::= prefixexp ‘.’ Name

对全局变量 x 的操作等价于操作 _ENV.x 。 由于代码块编译的方式, _ENV 永远也不可能是一个全局名字 (参见§2.2)。

3.3 – 语句

Lua 支持所有与 Pascal 或是 C 类似的常见形式的语句, 这个集合包括赋值,控制结构,函数调用,还有变量声明。

3.3.1 – 语句块

语句块是一个语句序列,它们会按次序执行:

block ::= {stat}

Lua 支持 空语句 , 你可以用分号分割语句,也可以以分号开始一个语句块, 或是连着写两个分号:

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

当前的解析器总是有第一种结构来解析, 它会将开括号看成函数调用的参数传递开始处。 为了避免这种二义性, 在一条语句以小括号开头时,前面放一个分号是个好习惯:

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

一个语句块可以被显式的定界为单条语句:

stat ::= do block end

显式的对一个块定界通常用来控制内部变量声明的作用域。 有时,显式定界也用于在一个语句块中间插入 return (参见§3.3.4)。

3.3.2 – 代码块

Lua 的一个编译单元被称为一个 代码块 。 从句法构成上讲,一个代码块就是一个语句块。

chunk ::= block

Lua 把一个代码块当作一个拥有不定参数的匿名函数 (参见§3.4.11)来处理。 正是这样,代码块内可以定义局部变量,它可以接收参数,返回若干值。 此外,这个匿名函数在编译时还为它的作用域绑定了一个外部局部变量 _ENV (参见§2.2)。 该函数总是把 _ENV 作为它唯一的一个上值, 即使这个函数不使用这个变量,它也存在。

代码块可以被保存在文件中,也可以作为宿主程序内部的一个字符串。 要执行一个代码块, 首先要让 Lua 加载 它, 将代码块中的代码预编译成虚拟机中的指令, 而后,Lua 用虚拟机解释器来运行编译后的代码。

代码块可以被预编译为二进制形式; 参见程序 luac 以及函数 string.dump 可获得更多细节。 用源码表示的程序和编译后的形式可自由替换; Lua 会自动检测文件格式做相应的处理 (参见 load )。

3.3.3 – 赋值

Lua 允许多重赋值。 因此,赋值的语法定义是等号左边放一个变量列表, 而等号右边放一个表达式列表。 两边的列表中的元素都用逗号间开:

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

表达式放在§3.4中讨论。

在作赋值操作之前, 那值列表会被 调整 为左边变量列表的个数。 如果值比需要的更多的话,多余的值就被扔掉。 如果值的数量不够需求, 将会按所需扩展若干个 nil 。 如果表达式列表以一个函数调用结束, 这个函数所返回的所有值都会在调整操作之前被置入值列表中 (除非这个函数调用被用括号括了起来;参见§3.4)。

赋值语句首先让所有的表达式完成运算, 之后再做赋值操作。 因此,下面这段代码

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

会把 a[3] 设置为 20,而不会影响到 a[4] 。 这是因为 a[i] 中的 i 在被赋值为 4 之前就被计算出来了(当时是 3 )。 简单说 ,这样一行

x, y = y, x

会交换 xy 的值, 及

x, y, z = y, z, x

会轮换 xyz 的值。

对全局变量以及表的域的赋值操作的含义可以通过元表来改变。 对 t[i] = val 这样的变量索引赋值, 等价于 settable_event(t,i,val) 。 (关于函数 settable_event 的详细说明,参见§2.4。 这个函数并没有在 Lua 中定义出来,也不可以被调用。 这里我们列出来,仅仅出于方便解释的目的。)

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

3.3.4 – 控制结构

if , while , and repeat 这些控制结构符合通常的意义,而且也有类似的语法:

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 被用来结束 whilerepeat 、或 for 循环, 它将跳到循环外接着之后的语句运行:

stat ::= break

break 跳出最内层的循环。

return 被用于从函数或是代码块(其实它就是一个函数) 中返回值。 函数可以返回不只一个值,所以 return 的语法为

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

return 只能被写在一个语句块的最后一句。 如果你真的需要从语句块的中间 return , 你可以使用显式的定义一个内部语句块, 一般写作 do return end 。 可以这样写是因为现在 return 成了(内部)语句块的最后一句了。

3.3.5 – For 语句

for 有两种形式:一种是数字形式,另一种是通用形式。

数字形式的 for 循环,通过一个数学运算不断地运行内部的代码块。 下面是它的语法:

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

block 将把 name 作循环变量。 从第一个 exp 开始起,直到第二个 exp 的值为止, 其步长为第三个 exp 。 更确切的说,一个 for 循环看起来是这个样子

for v = e1, e2, e3 do block end

这等价于代码:

do        local var, limit, step = tonumber(e1), tonumber(e2), tonumber(e3)        if not (var and limit and step) then error() end        var = var - step        while true do          var = var + step          if (step >= 0 and var > limit) or (step < 0 and var < limit) then            break          end          local v = var          block        end      end

注意下面这几点:

  • 所有三个控制表达式都只被运算一次, 表达式的计算在循环开始之前。 这些表达式的结果必须是数字。
  • varlimit ,以及 step 都是一些不可见的变量。 这里给它们起的名字都仅仅用于解释方便。
  • 如果第三个表达式(步长)没有给出,会把步长设为 1 。
  • 你可以用 breakgoto 来退出 for 循环。
  • 循环变量 v 是一个循环内部的局部变量; 如果你需要在循环结束后使用这个值, 在退出循环前把它赋给另一个变量。

通用形式的 for 通过一个叫作 迭代器 的函数工作。 每次迭代,迭代器函数都会被调用以产生一个新的值, 当这个值为 nil 时,循环停止。 通用形式的 for 循环的语法如下:

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

这样的 for 语句

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

它等价于这样一段代码:

do        local f, s, var = explist        while true do          local var_1, ···, var_n = f(s, var)          if var_1 == nil then break end          var = var_1          block        end      end

注意以下几点:

  • explist 只会被计算一次。 它返回三个值, 一个 迭代器 函数, 一个 状态 , 一个 迭代器的初始值
  • fs ,与 var 都是不可见的变量。 这里给它们起的名字都只是为了解说方便。
  • 你可以使用 break 来跳出 for 循环。
  • 环变量 var_i 对于循环来说是一个局部变量; 你不可以在 for 循环结束后继续使用。 如果你需要保留这些值,那么就在循环跳出或结束前赋值到别的变量里去。

3.3.6 – 函数调用语句

为了允许使用函数的副作用, 函数调用可以被作为一个语句执行:

stat ::= functioncall

在这种情况下,所有的返回值都被舍弃。 函数调用在§3.4.10中解释。

3.3.7 – 局部声明

局部变量可以在语句块中任何地方声明。 声明可以包含一个初始化赋值操作:

stat ::= local namelist [‘=’ explist]

如果有初始化值的话,初始化赋值操作的语法和赋值操作一致 (参见§3.3.3)。 若没有初始化值,所有的变量都被初始化为 nil

一个代码块同时也是一个语句块(参见§3.3.2), 所以局部变量可以放在代码块中那些显式注明的语句块之外。

局部变量的可见性规则在§3.5中解释。

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中解释。 可变参数的表达式写作三个点(' ... '), 它只能在有可变参数的函数中直接使用;这些在§3.4.11中解释。

二元操作符包含有数学运算操作符(参见§3.4.1), 位操作符(参见§3.4.2), 比较操作符(参见§3.4.4), 逻辑操作符(参见§3.4.5), 以及连接操作符(参见§3.4.6)。 一元操作符包括负号(参见§3.4.1), 按位非(参见§3.4.2), 逻辑非(参见§3.4.5), 和取长度操作符(参见§3.4.7)。

函数调用和可变参数表达式都可以放在多重返回值中。 如果函数调用被当作一条语句(参见§3.3.6), 其返回值列表被调整为零个元素,即抛弃所有的返回值。 如果表达式被用于表达式列表的最后(或是唯一的)一个元素, 那么不会做任何调整(除非表达式被括号括起来)。 在其它情况下, Lua 都会把结果调整为一个元素置入表达式列表中, 即保留第一个结果而忽略之后的所有值,或是在没有结果时, 补单个 nil

这里有一些例子:

f()    -- 调整为 0 个结果  g(f(), x)  -- f() 会被调整为一个结果  g(x, f())  -- g 收到 x 以及 f() 返回的所有结果  a,b,c = f(), x -- f() 被调整为 1 个结果 (c 收到 nil)  a,b = ...  -- a 收到可变参数列表的第一个参数,         -- b 收到第二个参数(如果可变参数列表中         -- 没有实际的参数,a 和 b 都会收到 nil)  a,b,c = x, f() -- f() 被调整为 2 个结果  a,b,c = f()    -- f() 被调整为 3 个结果  return f()     -- 返回 f() 的所有返回结果  return ...     -- 返回从可变参数列表中接收到的所有参数parameters  return x,y,f() -- 返回 x, y, 以及 f() 的所有返回值  {f()}      -- 用 f() 的所有返回值创建一个列表  {...}      -- 用可变参数中的所有值创建一个列表  {f(), nil}     -- f() 被调整为一个结果 

被括号括起来的表达式永远被当作一个值。 所以, (f(x,y,z)) 即使 f 返回多个值, 这个表达式永远是一个单一值。 ( (f(x,y,z)) 的值是 f 返回的第一个值。 如果 f 不返回值的话,那么它的值就是 nil 。)

3.4.1 – 数学运算操作符

Lua 支持下列数学运算操作符:

  • + : 加法
  • - : 减法
  • * : 乘法
  • / : 浮点除法
  • // : 向下取整除法
  • % : 取模
  • ^ : 乘方
  • - : 取负

除了乘方和浮点除法运算, 数学运算按如下方式工作: 如果两个操作数都是整数, 该操作以整数方式操作且结果也将是一个整数。 否则,当两个操作数都是数字或可以被转换为数字的字符串 (参见§3.4.3)时, 操作数会被转换成两个浮点数, 操作按通常的浮点规则(一般遵循 IEEE 754 标准) 来进行,结果也是一个浮点数。

乘方和浮点除法 ( / ) 总是把操作数转换成浮点数进行,起结果总是浮点数。 乘方使用 ISO C 函数 pow , 因此它也可以接受非整数的指数。

向下取整的除法 ( // ) 指做一次除法,并将商圆整到靠近负无穷的一侧, 即对操作数做除法后取 floor 。

取模被定义成除法的余数,其商被圆整到靠近负无穷的一侧(向下取整的除法)。

对于整数数学运算的溢出问题, 这些操作采取的策略是按通常遵循的以 2 为补码的数学运算的 环绕 规则。 (换句话说,它们返回其运算的数学结果对 2 64 取模后的数字。)

3.4.2 – 位操作符

Lua 支持下列位操作符:

  • & : 按位与
  • | : 按位或
  • ~ : 按位异或
  • >> : 右移
  • << : 左移
  • ~ : 按位非

所有的位操作都将操作数先转换为整数 (参见§3.4.3), 然后按位操作,其结果是一个整数。

对于右移和左移,均用零来填补空位。 移动的位数若为负,则向反方向位移; 若移动的位数的绝对值大于等于 整数本身的位数,其结果为零 (所有位都被移出)。

3.4.3 – 强制转换

Lua 对一些类型和值的内部表示会在运行时做一些数学转换。 位操作总是将浮点操作数转换成整数。 乘方和浮点除法总是将整数转换为浮点数。 其它数学操作若针对混合操作数 (整数和浮点数)将把整数转换为浮点数; 这一点被称为 通常规则 。 C API 同样会按需把整数转换为浮点数以及 把浮点数转换为整数。 此外,字符串连接操作除了字符串,也可以接受数字作为参数。

当操作需要数字时,Lua 还会把字符串转换为数字。

当把一个整数转换为浮点数时, 若整数值恰好可以表示为一个浮点数,那就取那个浮点数。 否则,转换会取最接近的较大值或较小值来表示这个数。 这种转换是不会失败的。

将浮点数转为整数的过程会检查 浮点数能否被准确的表达为一个整数 (即,浮点数是一个整数值且在整数可以表达的区间)。 如果可以,结果就是那个数,否则转换失败。

从字符串到数字的转换过程遵循以下流程: 首先,遵循按 Lua 词法分析器的规则分析语法来转换为对应的 整数或浮点数。 (字符串可以有前置或后置的空格以及一个符号。) 然后,结果数字再按前述副转换为所需要的类型(浮点或整数)。

从数字转换为字符串使用非制定的人可读的格式。 若想完全控制数字到字符串的转换过程, 可以使用字符串库中的 format 函数 (参见 string.format )。

3.4.4 – 比较操作符

Lua 支持下列比较操作符:

  • == : 等于
  • ~= : 不等于
  • < : 小于
  • > : 大于
  • <= : 小于等于
  • >= : 大于等于

这些操作的结果不是 false 就是 true

等于操作 ( == )先比较操作数的类型。 如果类型不同,结果就是 false 。 否则,继续比较值。 字符串按一般的方式比较。 数字遵循二元操作的规则: 如果两个操作数都是整数, 它们按整数比较; 否则,它们先转换为浮点数,然后再做比较。

表,用户数据,以及线程都按引用比较: 只有两者引用同一个对象时才认为它们相等。 每次你创建一个新对象(一张表,一个用户数据,或一个线程), 新对象都一定和已有且存在的对象不同。 相同引用的闭包一定相等。 有任何可察觉的差异(不同的行为,不同的定义)一定不等。

你可以通过使用 "eq" 元方法(参见§2.4) 来改变 Lua 比较表和用户数据时的方式。

等于操作不会将字符串转换为数字,反之亦然。 即, "0"==0 结果为 false , 且 t[0]t["0"] 指代着表中的不同项。

~= 操作完全等价于 ( == ) 操作的反值。

大小比较操作以以下方式进行。 如果参数都是数字, 它们按二元操作的常规进行。 否则,如果两个参数都是字符串, 它们的值按当前的区域设置来比较。 再则,Lua 就试着调用 "lt" 或是 "le" 元方法 (参见§2.4)。 a > b 的比较被转译为 b < aa >= b 被转译为 b <= a

3.4.5 – 逻辑操作符

Lua 中的逻辑操作符有 andor ,以及 not 。 和控制结构(参见§3.3.4)一样, 所有的逻辑操作符把 falsenil 都作为假, 而其它的一切都当作真。

取反操作 not 总是返回 falsetrue 中的一个。 与操作符 and 在第一个参数为 falsenil 时 返回这第一个参数; 否则, and 返回第二个参数。 或操作符 or 在第一个参数不为 nil 也不为 false 时, 返回这第一个参数,否则返回第二个参数。 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 – 取长度操作符

取长度操作符写作一元前置符 # 。 字符串的长度是它的字节数(就是以一个字符一个字节计算的字符串长度)。

程序可以通过 __len 元方法(参见§2.4) 来修改对字符串类型外的任何值的取长度操作行为。

如果 __len 元方法没有给出, 表 t 的长度只在表是一个 序列 时有定义。 序列指表的正数键集等于 {1..n} , 其中 n 是一个非负整数。 在这种情况下, n 是表的长度。 注意这样的表

{10, 20, nil, 40}

不是一个序列,因为它有键 却没有键 。 (因此,该表的正整数键集不等于 {1..n} 集合,故而就不存在 n 。) 注意,一张表是否是一个序列和它的非数字键无关。

3.4.8 – 优先级

Lua 中操作符的优先级写在下表中,从低到高优先级排序:

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

通常, 你可以用括号来改变运算次序。 连接操作符 (' .. ') 和乘方操作 (' ^ ') 是从右至左的。 其它所有的操作都是从左至右。

3.4.9 – 表构建

表构造子是一个构造表的表达式。 每次构造子被执行,都会构造出一张新的表。 构造子可以被用来构造一张空表, 也可以用来构造一张表并初始化其中的一些域。 一般的构造子的语法如下

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 }

等价于

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 , 而且其表达式是一个函数调用或者是一个可变参数, 那么这个表达式所有的返回值将依次进入列表 (参见§3.4.10)。

初始化域表可以在最后多一个分割符, 这样设计可以方便由机器生成代码。

3.4.10 – 函数调用

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

functioncall ::= prefixexp args

数调用时, 第一步,prefixexp 和 args 先被求值。 如果 prefixexp 的值的类型是 function , 那么这个函数就被用给出的参数调用。 否则 prefixexp 的元方法 "call" 就被调用, 第一个参数是 prefixexp 的值, 接下来的是原来的调用参数 (参见§2.4)。

这样的形式

functioncall ::= prefixexp ‘:’ Name args

可以用来调用 "方法"。 这是 Lua 支持的一种语法糖。 像 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 这样的调用形式将触发一次 尾调用 。 Lua 实现了 完全尾调用 (或称为 完全尾递归 ): 在尾调用中, 被调用的函数重用调用它的函数的堆栈项。 因此,对于程序执行的嵌套尾调用的层数是没有限制的。 然而,尾调用将删除调用它的函数的任何调试信息。 注意,尾调用只发生在特定的语法下, 仅当 return 只有单一函数调用作为参数时才发生尾调用; 这种语法使得调用函数的所有结果可以完整地返回。 因此,下面这些例子都不是尾调用:

return (f(x))        -- 返回值被调整为一个      return 2 * f(x)      return x, f(x)       -- 追加若干返回值      f(x); return         -- 返回值全部被舍弃      return x or f(x)     -- 返回值被调整为一个

3.4.11 – 函数定义

函数定义的语法如下:

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

另外定义了一些语法糖简化函数定义的写法:

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

该语句

function f () body end

被转译成

f = function () body end

该语句

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

被转译成

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

该语句

local function f () body end

被转译成

local f; f = function () body end

而不是

local f = function () body end

(这个差别只在函数体内需要引用 f 时才有。)

一个函数定义是一个可执行的表达式, 执行结果是一个类型为 function 的值。 当 Lua 预编译一个代码块时, 代码块作为一个函数,整个函数体也就被预编译了。 那么,无论何时 Lua 执行了函数定义, 这个函数本身就进行了 实例化 (或者说是 关闭 了)。 这个函数的实例(或者说是 闭包 )是表达式的最终值。

形参被看作是一些局部变量, 它们将由实参的值来初始化:

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

当一个函数被调用, 如果函数并非一个 可变参数函数 , 即在形参列表的末尾注明三个点 (' ... '), 那么实参列表就会被调整到形参列表的长度。 变长参数函数不会调整实参列表; 取而代之的是,它将把所有额外的参数放在一起通过 变长参数表达式 传递给函数, 其写法依旧是三个点。 这个表达式的值是一串实参值的列表, 看起来就跟一个可以返回多个结果的函数一样。 如果一个变长参数表达式放在另一个表达式中使用, 或是放在另一串表达式的中间, 那么它的返回值就会被调整为单个值。 若这个表达式放在了一系列表达式的最后一个, 就不会做调整了 (除非这最后一个参数被括号给括了起来)。

我们先做如下定义,然后再来看一个例子:

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, ... -->  (nothing)  g(3, 4)  a=3, b=4,   ... -->  (nothing)  g(3, 4, 5, 8)    a=3, b=4,   ... -->  5  8  g(5, r())    a=5, b=1,   ... -->  2  3 

结果由 return 来返回(参见§3.3.4)。 如果执行到函数末尾依旧没有遇到任何 return 语句, 函数就不会返回任何结果。

关于函数可返回值的数量限制和系统有关。 这个限制一定大于 1000 。

冒号 语法可以用来定义 方法 , 就是说,函数可以有一个隐式的形参 self 。 因此,如下语句

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

是这样一种写法的语法糖

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

3.5 – 可见性规则

Lua 语言有词法作用范围。 变量的作用范围开始于声明它们之后的第一个语句段, 结束于包含这个声明的最内层语句块的最后一个非空语句。 看下面这些例子:

x = 10                -- 全局变量      do                    -- 新的语句块        local x = x         -- 新的一个 'x', 它的值现在是 10        print(x)            --> 10        x = x+1        do                  -- 另一个语句块          local x = x+1     -- 又一个 'x'          print(x)          --> 12        end        print(x)            --> 11      end      print(x)              --> 10 (取到的是全局的那一个)

注意这里,类似 local x = x 这样的声明, 新的 x 正在被声明,但是还没有进入它的作用范围, 所以第二个 x 指向的是外面一层的变量。

因为有这样一个词法作用范围的规则, 局部变量可以被在它的作为范围内定义的函数自由使用。 当一个局部变量被内层的函数中使用的时候, 它被内层函数称作 上值 ,或是 外部局部变量

注意,每次执行到一个 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

4 – 编程接口

这个部分描述了 Lua 的 C API , 也就是宿主程序跟 Lua 通讯用的一组 C 函数。 所有的 API 函数按相关的类型以及常量都声明在头文件 lua.h 中。

虽然我们说的是“函数”, 但一部分简单的 API 是以宏的形式提供的。 除非另有说明, 所有的这些宏都只使用它们的参数一次 (除了第一个参数,那一定是 Lua 状态), 因此你不需担心这些宏的展开会引起一些副作用。

C 库中所有的 Lua API 函数都不去检查参数是否相容及有效。 然而,你可以在编译 Lua 时加上打开一个宏开关 LUA_USE_APICHECK 来改变这个行为。

4.1 –

Lua 使用一个 虚拟栈 来和 C 互传值。 栈上的的每个元素都是一个 Lua 值 ( nil ,数字,字符串,等等)。

无论何时 Lua 调用 C,被调用的函数都得到一个新的栈, 这个栈独立于 C 函数本身的栈,也独立于之前的 Lua 栈。 它里面包含了 Lua 传递给 C 函数的所有参数, 而 C 函数则把要返回的结果放入这个栈以返回给调用者 (参见 lua_CFunction )。

方便起见, 所有针对栈的 API 查询操作都不严格遵循栈的操作规则。 而是可以用一个 索引 来指向栈上的任何元素: 正的索引指的是栈上的绝对位置(从一开始); 负的索引则指从栈顶开始的偏移量。 展开来说,如果堆栈有 n 个元素, 那么索引 1 表示第一个元素 (也就是最先被压栈的元素) 而索引 n 则指最后一个元素; 索引 -1 也是指最后一个元素 (即栈顶的元素), 索引 -n 是指第一个元素。

4.2 – 栈大小

当你使用 Lua API 时, 就有责任保证做恰当的调用。 特别需要注意的是, 你有责任控制不要堆栈溢出 。 你可以使用 lua_checkstack 这个函数来扩大可用堆栈的尺寸。

无论何时 Lua 调用 C , 它都只保证至少有 LUA_MINSTACK 这么多的堆栈空间可以使用。 LUA_MINSTACK 一般被定义为 20 , 因此,只要你不是不断的把数据压栈, 通常你不用关心堆栈大小。

当你调用一个 Lua 函数却没有指定要接收多少个返回值时 (参见 lua_call ), Lua 可以保证栈一定有足够的空间来接收所有的返回值, 但不保证此外留有额外的空间。 因此,在做了一次这样的调用后,如果你需要继续压栈, 则需要使用 lua_checkstack

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

API 中的函数若需要传入栈索引,这个索引必须是 有效索引 或是 可接受索引

有效索引 指引用栈内真实位置的索引; 即在 1 到栈顶之间的位置 ( 1 ≤ abs(index) ≤ top )。 通常,一个可能修改该位置的值的函数需要传入有效索引。

除非另有说明, 任何可以接受有效索引的函数同时也接受 伪索引 。 伪索引指代一些可以被 C code 访问得到 Lua 值,而它们又不在栈内。 这用于访问注册表以及 C 函数的上值(参见§4.4)。

对于那些只是需要栈中的值(例如查询函数) 而不需要指定一个栈位置的函数, 可以用一个可接受的索引去调用它们。 可接受索引 不仅可以是任何包括伪索引在内的有效索引, 还可以是任何超过栈顶但落下为栈分配出来的空间内的正索引。 (注意 0 永远都不是一个可接受索引。) 除非另有说明,API 里的函数都接受可接受索引。

允许可接受索引是为了避免对栈顶以外的查询时做额外的检查。 例如,C 函数可以直接查询传给它的第三个参数, 而不用先检查是不是有第三个参数, 即不需要检查 3 是不是一个有效索引。

对于那些以可接受索引调用的函数, 无效索引被看作包含了一个虚拟类型 LUA_TNONE 的值, 这个值的行为和 nil 一致。

4.4 – C 闭包

当 C 函数被创建出来, 我们有可能会把一些值关联在一起, 也就是创建一个 C 闭包 (参见 lua_pushcclosure ); 这些被关联起来的值被叫做 上值 , 它们可以在函数被调用的时候访问的到。

无论何时去调用 C 函数, 函数的上值都可以用伪索引定位。 我们可以用 lua_upvalueindex 这个宏来生成这些伪索引。 第一个关联到函数的值放在 lua_upvalueindex(1) 位置处,依此类推。 使用 lua_upvalueindex(n) 时, 若 n 大于当前函数的总上值个数 (但不可以大于 256)会产生一个可接受的但无效的索引。

4.5 – 注册表

Lua 提供了一个 注册表 , 这是一个预定义出来的表, 可以用来保存任何 C 代码想保存的 Lua 值。 这个表可以用有效伪索引 LUA_REGISTRYINDEX 来定位。 任何 C 库都可以在这张表里保存数据, 为了防止冲突,你需要特别小心的选择键名。 一般的用法是,你可以用一个包含你的库名的字符串做为键名, 或者取你自己 C 对象的地址,以轻量用户数据的形式做键, 还可以用你的代码创建出来的任意 Lua 对象做键。 关于变量名,字符串键名中以下划线加大写字母的名字被 Lua 保留。

注册表中的整数键用于引用机制 (参见 luaL_ref ), 以及一些预定义的值。 因此,整数键不要用于别的目的。

当你创建了一个新的 Lua 状态机, 其中的注册表内就预定义好了几个值。 这些预定义值可以用整数索引到, 这些整数以常数形式定义在 lua.h 中。 有下列常数:

  • LUA_RIDX_MAINTHREAD : 注册表中这个索引下是状态机的主线程。 (主线程和状态机同时被创建出来。)
  • LUA_RIDX_GLOBALS : 注册表的这个索引下是全局环境。

4.6 – C 中的错误处理

在内部实现中,Lua 使用了 C 的 longjmp 机制来处理错误。 (如果你使用 C++ 编译,Lua 将换成异常; 细节请在源代码中搜索 LUAI_THROW 。) 当 Lua 碰到任何错误 (比如内存分配错误、类型错误、语法错误、还有运行时错误) 它都会 抛出 一个错误出去; 也就是调用一次长跳转。 在 保护环境 下, Lua 使用 setjmp 来设置一个恢复点; 任何发生的错误都会跳转到最近的一个恢复点。

如果错误发生在保护环境之外, Lua 会先调用 panic 函数 (参见 lua_atpanic ) 然后调用 abort 来退出宿主程序。 你的 panic 函数只要不返回 (例如:长跳转到你在 Lua 外你自己设置的恢复点) 就可以必须退出程序。

panic 函数以错误消息处理器(参见§2.3)的方式运行; 错误消息在栈顶。 不同的是,它不保证栈通奸。 做任何压栈操作前,panic 函数都必须先检查是否有足够的空间 (参见§4.2)。

大多数 API 函数都有可能抛出错误, 例如在内存分配错误时就会抛出。 每个函数的文档都会注明它是否可能抛出错误。

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

4.7 – C 中的让出处理

Lua 内部使用 C 的 longjmp 机制让出一个协程。 因此,如果一个 C 函数 foo 调用了一个 API 函数, 而这个 API 函数让出了(直接或间接调用了让出函数)。 由于 longjmp 会移除 C 栈的栈帧, Lua 就无法返回到 foo 里了。

为了回避这类问题, 碰到 API 调用中调用让出时,除了那些抛出错误的 API 外,还提供了三个函数: lua_yieldklua_callk ,和 lua_pcallk 。 它们在让出发生时,可以从传入的 延续函数 (名为 k 的参数)继续运行。

我们需要预设一些术语来解释延续点。 对于从 Lua 中调用的 C 函数,我们称之为 原函数 。 从这个原函数中调用的上面所述的三个 C API 函数我们称之为 被调函数 。 被调函数可以使当前线程让出。 (让出发生在被调函数是 lua_yieldk , 或传入 lua_callklua_pcallk 的函数调用了让出时。)

假设正在运行的线程在执行被调函数时让出。 当再次延续这条线程,它希望继续被调函数的运行。 然而,被调函数不可能返回到原函数中。 这是因为之前的让出操作破坏了 C 栈的栈帧。 作为替代品,Lua 调用那个作为被调函数参数给出的 延续函数 。 正如其名,延续函数将延续原函数的任务。

下面的函数会做一个说明:

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 就是一个 延续函数 (函数类型为 lua_KFunction )。 它的工作就是原函数中调用 lua_pcall 之后做的那些事情。 现在我们必须通知 Lua 说,你必须在被 lua_pcall 执行得 Lua 代码发生过中断(错误或让出)后, 还得继续调用 k 。 所以我们还得继续改写这段代码,把 lua_pcall 替换成 lua_pcallk

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_YIELD 。 (对这两个函数,Lua 不会因任何错误而调用延续函数。 因为它们并不处理错误。) 同样,当你使用 lua_callk 时, 你应该用 LUA_OK 作为状态码来调用延续函数。 (对于 lua_yieldk , 几乎没有什么地方需要直接调用延续函数, 因为 lua_yieldk 本身并不会返回。)

Lua 会把延续函数看作原函数。 延续函数将接收到和原函数相同的 Lua 栈,其接收到的 lua 状态也和 被调函数若返回后应该有的状态一致。 (例如, lua_callk 调用之后, 栈中之前压入的函数和调用参数都被调用产生的返回值所替代。) 这时也有相同的上值。 等到它返回的时候,Lua 会将其看待成原函数的返回去操作。

4.8 – 函数和类型

这里按字母次序列出了所有 C API 中的函数和类型。 每个函数都有一个这样的提示: [-o, +p, x ]

对于第一个域, o , 指的是该函数会从栈上弹出多少个元素。 第二个域, p , 指该函数会将多少个元素压栈。 (所有函数都会在弹出参数后再把结果压栈。) x|y 这种形式的域表示该函数根据具体情况可能压入(或弹出) xy 个元素; 问号 ' ? ' 表示 我们无法仅通过参数来了解该函数会弹出/压入多少元素 (比如,数量取决于栈上有些什么)。 第三个域, x , 解释了该函数是否会抛出错误: ' - ' 表示该函数绝对不会抛出错误; ' e ' 表示该函数可能抛出错误; ' v ' 表示该函数可能抛出有意义的错误。

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 不是 NULLosizeptr 指向的内存块的尺寸, 即这个内存块当初被分配或重分配的尺寸。

如果 ptrNULLosize 是 Lua 即将分配对象类型的编码。 当(且仅当)Lua 创建一个对应类型的新对象时, osizeLUA_TSTRINGLUA_TTABLELUA_TFUNCTIONLUA_TUSERDATA ,或 LUA_TTHREAD 中的一个。 若 osize 是其它类型,Lua 将为其它东西分配内存。

Lua 假定分配器函数会遵循以下行为:

nsize 是零时, 分配器必须和 free 行为类似并返回 NULL

nsize 不是零时, 分配器必须和 realloc 行为类似。 如果分配器无法完成请求,返回 NULL 。 Lua 假定在 osize >= nsize 成立的条件下, 分配器绝不会失败。

这里有一个简单的分配器函数的实现。 这个实现被放在补充库中,供 luaL_newstate 使用。

static void *l_alloc (void *ud, void *ptr, size_t osize,                                                 size_t nsize) {        (void)ud;  (void)osize;  /* not used */        if (nsize == 0) {          free(ptr);          return NULL;        }        else          return realloc(ptr, nsize);      }

注意,标准 C 能确保 free(NULL) 没有副作用, 且 realloc(NULL,size) 等价于 malloc(size) 。 这段代码假定 realloc 在缩小块长度时不会失败。 (虽然标准 C 没有对此行为做出保证,但这看起来是一个安全的假定。)

lua_arith

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

void lua_arith (lua_State *L, int op);

对栈顶的两个值(或者一个,比如取反)做一次数学或位操作。 其中,栈顶的那个值是第二个操作数。 它会弹出压入的值,并把结果放在栈顶。 这个函数遵循 Lua 对应的操作符运算规则 (即有可能触发元方法)。

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

  • LUA_OPADD : 加法 ( + )
  • LUA_OPSUB : 减法 ( - )
  • LUA_OPMUL : 乘法 ( * )
  • LUA_OPDIV : 浮点除法 ( / )
  • LUA_OPIDIV : 向下取整的除法 ( // )
  • LUA_OPMOD : 取模 ( % )
  • LUA_OPPOW : 乘方 ( ^ )
  • LUA_OPUNM : 取负 (一元 - )
  • LUA_OPBNOT : 按位取反 ( ~ )
  • LUA_OPBAND : 按位与 ( & )
  • LUA_OPBOR : 按位或 ( | )
  • LUA_OPBXOR : 按位异或 ( ~ )
  • LUA_OPSHL : 左移 ( << )
  • LUA_OPSHR : 右移 ( >> )

lua_atpanic

[-0, +0, –]

lua_CFunction lua_atpanic (lua_State *L, lua_CFunction panicf);

设置一个新的 panic 函数,并返回之前设置的那个。 (参见§4.6)。

lua_call

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

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

调用一个函数。

要调用一个函数请遵循以下协议: 首先,要调用的函数应该被压入栈; 接着,把需要传递给这个函数的参数按正序压栈; 这是指第一个参数首先压栈。 最后调用一下 lua_callnargs 是你压入栈的参数个数。 当函数调用完毕后,所有的参数以及函数本身都会出栈。 而函数的返回值这时则被压栈。 返回值的个数将被调整为 nresults 个, 除非 nresults 被设置成 LUA_MULTRET 。 在这种情况下,所有的返回值都被压入堆栈中。 Lua 会保证返回值都放入栈空间中。 函数返回值将按正序压栈(第一个返回值首先压栈), 因此在调用结束后,最后一个返回值将被放在栈顶。

被调用函数内发生的错误将(通过 longjmp )一直上抛。

下面的例子中,这行 Lua 代码等价于在宿主程序中用 C 代码做一些工作:

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' */ 

注意上面这段代码是 平衡 的: 到了最后,堆栈恢复成原有的配置。 这是一种良好的编程习惯。

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

lua_CFunction

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

C 函数的类型。

为了正确的和 Lua 通讯, C 函数必须使用下列协议。 这个协议定义了参数以及返回值传递方法: C 函数通过 Lua 中的栈来接受参数, 参数以正序入栈(第一个参数首先入栈)。 因此,当函数开始的时候, lua_gettop(L) 可以返回函数收到的参数个数。 第一个参数(如果有的话)在索引 1 的地方, 而最后一个参数在索引 lua_gettop(L) 处。 当需要向 Lua 返回值的时候, C 函数只需要把它们以正序压到堆栈上(第一个返回值最先压入), 然后返回这些返回值的个数。 在这些返回值之下的,堆栈上的东西都会被 Lua 丢掉。 和 Lua 函数一样,从 Lua 中调用 C 函数也可以有很多返回值。

下面这个例子中的函数将接收若干数字参数,并返回它们的平均数与和:

static int foo (lua_State *L) {        int n = lua_gettop(L);    /* 参数的个数 */        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);        /* 第一个返回值 */        lua_pushnumber(L, sum);         /* 第二个返回值 */        return 2;                   /* 返回值的个数 */      }

lua_checkstack

[-0, +0, –]

int lua_checkstack (lua_State *L, int n);

确保堆栈上至少有 n 个额外空位。 如果不能把堆栈扩展到相应的尺寸,函数返回假。 失败的原因包括将把栈扩展到比固定最大尺寸还大 (至少是几千个元素)或分配内存失败。 这个函数永远不会缩小堆栈; 如果堆栈已经比需要的大了,那么就保持原样。

lua_close

[-0, +0, –]

void lua_close (lua_State *L);

销毁指定 Lua 状态机中的所有对象 (如果有垃圾收集相关的元方法的话,会调用它们), 并且释放状态机中使用的所有动态内存。 在一些平台上,你可以不必调用这个函数, 因为当宿主程序结束的时候,所有的资源就自然被释放掉了。 另一方面,长期运行的程序,比如一个后台程序或是一个网站服务器, 会创建出多个 Lua 状态机。那么就应该在不需要时赶紧关闭它们。

lua_compare

[-0, +0, e ]

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

比较两个 Lua 值。 当索引 index1 处的值通过 op 和索引 index2 处的值做比较后条件满足,函数返回 1 。 这个函数遵循 Lua 对应的操作规则(即有可能触发元方法)。 反之,函数返回 0。 当任何一个索引无效时,函数也会返回 0 。

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

  • LUA_OPEQ : 相等比较 ( == )
  • LUA_OPLT : 小于比较 ( < )
  • LUA_OPLE : 小于等于比较 ( <= )

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

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

创建一张新的空表压栈。 参数 narr 建议了这张表作为序列使用时会有多少个元素; 参数 nrec 建议了这张表可能拥有多少序列之外的元素。 Lua 会使用这些建议来预分配这张新表。 如果你知道这张表用途的更多信息,预分配可以提高性能。 否则,你可以使用函数 lua_newtable

lua_dump

[-0, +0, e ]

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

把函数导出成二进制代码块 。 函数接收栈顶的 Lua 函数做参数, 然后生成它的二进制代码块。 若被导出的东西被再次加载, 加载的结果就相当于原来的函数。 当它在产生代码块的时候, lua_dump 通过调用函数 writer (参见 lua_Writer ) 来写入数据,后面的 data 参数会被传入 writer

如果 strip 为真, 二进制代码块将不包含该函数的调试信息。

最后一次由 writer 的返回值将作为这个函数的返回值返回; 0 表示没有错误。

该函数不会把 Lua 函数弹出堆栈。

lua_error

[-1, +0, v ]

int lua_error (lua_State *L);

以栈顶的值作为错误对象,抛出一个 Lua 错误。 这个函数将做一次长跳转,所以一定不会返回 (参见 luaL_error )。

lua_gc

[-0, +0, e ]

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

控制垃圾收集器。

这个函数根据其参数 what 发起几种不同的任务:

  • LUA_GCSTOP : 停止垃圾收集器。
  • LUA_GCRESTART : 重启垃圾收集器。
  • LUA_GCCOLLECT : 发起一次完整的垃圾收集循环。
  • LUA_GCCOUNT : 返回 Lua 使用的内存总量(以 K 字节为单位)。
  • LUA_GCCOUNTB : 返回当前内存使用量除以 1024 的余数。
  • LUA_GCSTEP : 发起一步增量垃圾收集。
  • LUA_GCSETPAUSE : data 设为 垃圾收集器间歇率 (参见§2.5),并返回之前设置的值。
  • LUA_GCSETSTEPMUL : data 设为 垃圾收集器步进倍率 (参见§2.5),并返回之前设置的值。
  • LUA_GCISRUNNING : 返回收集器是否在运行(即没有停止)。

关于这些选项的细节,参见 collectgarbage

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 不会使用它。

每一个新线程都会携带一块内存, 初始化为主线程的这块内存的副本。

默认配置下,这块内存的大小为空指针的大小。 不过你可以重新编译 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_getuservalue

[-0, +1, –]

int lua_getuservalue (lua_State *L, int index);

将给定索引处的用户数据所关联的 Lua 值压栈。

返回压入值的类型。

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

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

当给定索引的值是一个轻量用户数据时,返回 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);

当给定索引的值是一个用户数据(无论是完全的还是轻量的)时, 返回 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.7)。

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 代码块,但不运行它。 如果没有错误, lua_load 把一个编译好的代码块作为一个 Lua 函数压到栈顶。 否则,压入错误消息。

lua_load 的返回值可以是:

  • LUA_OK : 没有错误;
  • LUA_ERRSYNTAX : 在预编译时碰到语法错误;
  • LUA_ERRMEM : 内存分配错误;
  • LUA_ERRGCMM : 在运行 __gc 元方法时出错了。 (这个错误和代码块加载过程无关,它是由垃圾收集器引发的。)

lua_load 函数使用一个用户提供的 reader 函数来读取代码块(参见 lua_Reader )。 data 参数会被传入 reader 函数。

chunkname 这个参数可以赋予代码块一个名字, 这个名字被用于出错信息和调试信息(参见§4.9)。

lua_load 会自动检测代码块是文本的还是二进制的, 然后做对应的加载操作(参见程序 luac )。 字符串 mode 的作用和函数 load 一致。 它还可以是 NULL 等价于字符串 " bt "。

lua_load 的内部会使用栈, 因此 reader 函数必须永远在每次返回时保留栈的原样。

如果返回的函数有上值, 第一个上值会被设置为 保存在注册表(参见§4.5) LUA_RIDX_GLOBALS 索引处的全局环境。 在加载主代码块时,这个上值是 _ENV 变量(参见§2.2)。 其它上值均被初始化为 nil

lua_newstate

[-0, +0, –]

lua_State *lua_newstate (lua_Alloc f, void *ud);

创建一个运行在新的独立的状态机中的线程。 如果无法创建线程或状态机(由于内存有限)则返回 NULL 。 参数 f 是一个分配器函数; Lua 将通过这个函数做状态机内所有的内存分配操作。 第二个参数 ud ,这个指针将在每次调用分配器时被转入。

lua_newtable

[-0, +1, e ]

void lua_newtable (lua_State *L);

创建一张空表,并将其压栈。 它等价于 lua_createtable(L, 0, 0)

lua_newthread

[-0, +1, e ]

lua_State *lua_newthread (lua_State *L);

创建一条新线程,并将其压栈, 并返回维护这个线程的 lua_State 指针。 这个函数返回的新线程共享原线程的全局环境, 但是它有独立的运行栈。

没有显式的函数可以用来关闭或销毁掉一个线程。 线程跟其它 Lua 对象一样是垃圾收集的条目之一。

lua_newuserdata

[-0, +1, e ]

void *lua_newuserdata (lua_State *L, size_t size);

这个函数分配分配一块指定大小的内存块, 把内存块地址作为一个完全用户数据压栈, 并返回这个地址。 宿主程序可以随意使用这块内存。

lua_next

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

int lua_next (lua_State *L, int index);

从栈顶弹出一个键, 然后把索引指定的表中的一个键值对压栈 (弹出的键之后的 “下一” 对)。 如果表中以无更多元素, 那么 lua_next 将返回 0 (什么也不压栈)。

典型的遍历方法是这样的:

/*  表放在索引 't' 处 */      lua_pushnil(L);  /* 第一个键 */      while (lua_next(L, t) != 0) {  /* 使用 '键' (在索引 -2 处) 和 '值' (在索引 -1 处)*/  printf("%s - %s/n",   lua_typename(L, lua_type(L, -2)),   lua_typename(L, lua_type(L, -1)));  /* 移除 '值' ;保留 '键' 做下一次迭代 */  lua_pop(L, 1);      } 

在遍历一张表的时候, 不要直接对键调用 lua_tolstring , 除非你知道这个键一定是一个字符串。 调用 lua_tolstring 有可能改变给定索引位置的值; 这会对下一次调用 lua_next 造成影响。

关于迭代过程中修改被迭代的表的注意事项参见 next 函数。

lua_Number

typedef double lua_Number;

Lua 中浮点数的类型。

Lua 中数字的类型。确省是 double ,但是你改成 float 。 (参见 luaconf.h 中的 LUA_REAL 。)

lua_numbertointeger

int lua_numbertointeger (lua_Number n, lua_Integer *p);

将一个 Lua 浮点数转换为一个 Lua 整数。 这个宏假设 n 有对应的整数值。 如果该值在 Lua 整数可表示范围内, 就将其转换为一个整数赋给 *p 。 宏的结果是一个布尔量,表示转换是否成功。 (注意、由于圆整关系,这个范围测试不用此宏很难做对。)

该宏有可能对其参数做多次取值。

lua_pcall

[-(nargs + 1), +(nresults|1), –]

int lua_pcall (lua_State *L, int nargs, int nresults, int msgh);

以保护模式调用一个函数。

nargsnresults 的含义与 lua_call 中的相同。 如果在调用过程中没有发生错误, lua_pcall 的行为和 lua_call 完全一致。 但是,如果有错误发生的话, lua_pcall 会捕获它, 然后把唯一的值(错误消息)压栈,然后返回错误码。 同 lua_call 一样, lua_pcall 总是把函数本身和它的参数从栈上移除。

如果 msgh 是 0 , 返回在栈顶的错误消息就和原始错误消息完全一致。 否则, msgh 就被当成是 错误处理函数 在栈上的索引位置。 (在当前的实现里,这个索引不能是伪索引。) 在发生运行时错误时, 这个函数会被调用而参数就是错误消息。 错误处理函数的返回值将被 lua_pcall 作为错误消息返回在堆栈上。

典型的用法中,错误处理函数被用来给错误消息加上更多的调试信息, 比如栈跟踪信息。 这些信息在 lua_pcall 返回后, 由于栈已经展开,所以收集不到了。

lua_pcall 函数会返回下列常数 (定义在 lua.h 内)中的一个:

  • LUA_OK (0): 成功。
  • LUA_ERRRUN : 运行时错误。
  • LUA_ERRMEM : 内存分配错误。对于这种错,Lua 不会调用错误处理函数。
  • LUA_ERRERR : 在运行错误处理函数时发生的错误。
  • LUA_ERRGCMM : 在运行 __gc 元方法时发生的错误。 (这个错误和被调用的函数无关。)

lua_pcallk

[-(nargs + 1), +(nresults|1), –]

int lua_pcallk (lua_State *L,  int nargs,  int nresults,  int msgh,  lua_KContext ctx,  lua_KFunction k); 

这个函数的行为和 lua_pcall 完全一致,只不过它还允许被调用的函数让出 (参见§4.7)。

lua_pop

[-n, +0, –]

void lua_pop (lua_State *L, int n);

从栈中弹出 n 个元素。

lua_pushboolean

[-0, +1, –]

void lua_pushboolean (lua_State *L, int b);

b 作为一个布尔量压栈。

lua_pushcclosure

[-n, +1, e ]

void lua_pushcclosure (lua_State *L, lua_CFunction fn, int n);

把一个新的 C 闭包压栈。

当创建了一个 C 函数后, 你可以给它关联一些值, 这就是在创建一个 C 闭包(参见§4.4); 接下来无论函数何时被调用,这些值都可以被这个函数访问到。 为了将一些值关联到一个 C 函数上, 首先这些值需要先被压入堆栈(如果有多个值,第一个先压)。 接下来调用 lua_pushcclosure 来创建出闭包并把这个 C 函数压到栈上。 参数 n 告之函数有多少个值需要关联到函数上。 lua_pushcclosure 也会把这些值从栈上弹出。

n 的最大值是 255 。

n 为零时, 这个函数将创建出一个 轻量 C 函数 , 它就是一个指向 C 函数的指针。 这种情况下,不可能抛出内存错误。

lua_pushcfunction

[-0, +1, –]

void lua_pushcfunction (lua_State *L, lua_CFunction f);

将一个 C 函数压栈。 这个函数接收一个 C 函数指针, 并将一个类型为 function 的 Lua 值压栈。 当这个栈顶的值被调用时,将触发对应的 C 函数。

注册到 Lua 中的任何函数都必须遵循正确的协议来接收参数和返回值 (参见 lua_CFunction )。

lua_pushcfunction 是作为一个宏定义出现的:

#define lua_pushcfunction(L,f)  lua_pushcclosure(L,f,0)

lua_pushfstring

[-0, +1, e ]

const char *lua_pushfstring (lua_State *L, const char *fmt, ...);

把一个格式化过的字符串压栈, 然后返回这个字符串的指针。 它和 C 函数 sprintf 比较像, 不过有一些重要的区别:

  • 你不需要为结果分配空间: 其结果是一个 Lua 字符串,由 Lua 来关心其内存分配 (同时通过垃圾收集来释放内存)。
  • 这个转换非常的受限。 不支持符号、宽度、精度。 转换符只支持 ' %% ' (插入一个字符 ' % '), ' %s ' (插入一个带零终止符的字符串,没有长度限制), ' %f ' (插入一个 lua_Number ), ' %L ' (插入一个 lua_Integer ), ' %p ' (插入一个指针或是一个十六进制数), ' %d ' (插入一个 int ), ' %c ' (插入一个用 int 表示的单字节字符),以及 ' %U ' (插入一个用 long int 表示的 UTF-8 字)。

lua_pushglobaltable

[-0, +1, –]

void lua_pushglobaltable (lua_State *L);

将全局环境压栈。

lua_pushinteger

[-0, +1, –]

void lua_pushinteger (lua_State *L, lua_Integer n);

把值为 n 的整数压栈。

lua_pushlightuserdata

[-0, +1, –]

void lua_pushlightuserdata (lua_State *L, void *p);

把一个轻量用户数据压栈。

用户数据是保留在 Lua 中的 C 值。 轻量用户数据 表示一个指针 void* 。 它是一个像数字一样的值: 你不需要专门创建它,它也没有独立的元表,而且也不会被收集(因为从来不需要创建)。 只要表示的 C 地址相同,两个轻量用户数据就相等。

lua_pushliteral

[-0, +1, e ]

const char *lua_pushliteral (lua_State *L, const char *s);

这个宏等价于 lua_pushlstring , 区别仅在于只能在 s 是一个字面量时才能用它。 它会自动给出字符串的长度。

lua_pushlstring

[-0, +1, e ]

const char *lua_pushlstring (lua_State *L, const char *s, size_t len);

把指针 s 指向的长度为 len 的字符串压栈。 Lua 对这个字符串做一个内部副本(或是复用一个副本), 因此 s 处的内存在函数返回后,可以释放掉或是立刻重用于其它用途。 字符串内可以是任意二进制数据,包括零字符。

返回内部副本的指针。

lua_pushnil

[-0, +1, –]

void lua_pushnil (lua_State *L);

将空值压栈。

lua_pushnumber

[-0, +1, –]

void lua_pushnumber (lua_State *L, lua_Number n);

把一个值为 n 的浮点数压栈。

lua_pushstring

[-0, +1, e ]

const char *lua_pushstring (lua_State *L, const char *s);

将指针 s 指向的零结尾的字符串压栈。 因此 s 处的内存在函数返回后,可以释放掉或是立刻重用于其它用途。

返回内部副本的指针。

如果 sNULL ,将 nil 压栈并返回 NULL

lua_pushthread

[-0, +1, –]

int lua_pushthread (lua_State *L);

L 表示的线程压栈。 如果这个线程是当前状态机的主线程的话,返回 1 。

lua_pushvalue

[-0, +1, –]

void lua_pushvalue (lua_State *L, int index);

把栈上给定索引处的元素作一个副本压栈。

lua_pushvfstring

[-0, +1, e ]

const char *lua_pushvfstring (lua_State *L,                               const char *fmt,                               va_list argp);

等价于 lua_pushfstring , 不过是用 va_list 接收参数,而不是用可变数量的实际参数。

lua_rawequal

[-0, +0, –]

int lua_rawequal (lua_State *L, int index1, int index2);

如果索引 index1 与索引 index2 处的值 本身相等(即不调用元方法),返回 1 。 否则返回 0 。 当任何一个索引无效时,也返回 0 。

lua_rawget

[-1, +1, –]

int lua_rawget (lua_State *L, int index);

类似于 lua_gettable , 但是作一次直接访问(不触发元方法)。

lua_rawgeti

[-0, +1, –]

int lua_rawgeti (lua_State *L, int index, lua_Integer n);

t[n] 的值压栈, 这里的 t 是指给定索引处的表。 这是一次直接访问;就是说,它不会触发元方法。

返回入栈值的类型。

lua_rawgetp

[-0, +1, –]

int lua_rawgetp (lua_State *L, int index, const void *p);

t[k] 的值压栈, 这里的 t 是指给定索引处的表,、 k 是指针 p 对应的轻量用户数据。 这是一次直接访问;就是说,它不会触发元方法。

返回入栈值的类型。

lua_rawlen

[-0, +0, –]

size_t lua_rawlen (lua_State *L, int index);

返回给定索引处值的固有“长度”: 对于字符串,它指字符串的长度; 对于表;它指不触发元方法的情况下取长度操作(' # ')应得到的值; 对于用户数据,它指为该用户数据分配的内存块的大小; 对于其它值,它为 0 。

lua_rawset

[-2, +0, e ]

void lua_rawset (lua_State *L, int index);

类似于 lua_settable , 但是是做一次直接赋值(不触发元方法)。

lua_rawseti

[-1, +0, e ]

void lua_rawseti (lua_State *L, int index, lua_Integer i);

等价于 t[i] = v , 这里的 t 是指给定索引处的表, 而 v 是栈顶的值。

这个函数会将值弹出栈。 赋值是直接的;即不会触发元方法。

lua_rawsetp

[-1, +0, e ]

void lua_rawsetp (lua_State *L, int index, const void *p);

等价于 t[k] = v , 这里的 t 是指给定索引处的表, k 是指针 p 对应的轻量用户数据。 而 v 是栈顶的值。

这个函数会将值弹出栈。 赋值是直接的;即不会触发元方法。

lua_Reader

typedef const char * (*lua_Reader) (lua_State *L,                                     void *data,                                     size_t *size);

lua_load 用到的读取器函数, 每次它需要一块新的代码块的时候, lua_load 就调用读取器, 每次都会传入一个参数 data 。 读取器需要返回含有新的代码块的一块内存的指针, 并把 size 设为这块内存的大小。 内存块必须在下一次函数被调用之前一直存在。 读取器可以通过返回 NULL 或设 size 为 0 来指示代码块结束。 读取器可能返回多个块,每个块可以有任意的大于零的尺寸。

lua_register

[-0, +0, e ]

void lua_register (lua_State *L, const char *name, lua_CFunction f);

把 C 函数 f 设到全局变量 name 中。 它通过一个宏定义:

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

从给定有效索引处移除一个元素, 把这个索引之上的所有元素移下来填补上这个空隙。 不能用伪索引来调用这个函数,因为伪索引并不指向真实的栈上的位置。

lua_replace

[-1, +0, –]

void lua_replace (lua_State *L, int index);

把栈顶元素放置到给定位置而不移动其它元素 (因此覆盖了那个位置处的值),然后将栈顶元素弹出。

lua_resume

[-?, +?, –]

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

在给定线程中启动或延续一条协程 。

要启动一个协程的话, 你需要把主函数以及它需要的参数压入线程栈; 然后调用 lua_resume , 把 nargs 设为参数的个数。 这次调用会在协程挂起时或是结束运行后返回。 当函数返回时,堆栈中会有传给 href="#lua_yield"> lua_yield 的所有值, 或是主函数的所有返回值。 当协程让出, lua_resume 返回 LUA_YIELD , 若协程结束运行且没有任何错误时,返回 0 。 如果有错则返回错误代码(参见 lua_pcall )。

在发生错误的情况下, 堆栈没有展开, 因此你可以使用调试 API 来处理它。 错误消息放在栈顶在。

要延续一个协程, 你需要清除上次 lua_yield 遗留下的所有结果, 你把需要传给 yield 作结果的值压栈, 然后调用 lua_resume

参数 from 表示协程从哪个协程中来延续 L 的。 如果不存在这样一个协程,这个参数可以是 NULL

lua_rotate

[-0, +0, –]

void lua_rotate (lua_State *L, int idx, int n);

把从 idx 开始到栈顶的元素轮转 n 个位置。 对于 n 为正数时,轮转方向是向栈顶的; 当 n 为负数时,向栈底方向轮转 -n 个位置。 n 的绝对值不可以比参于轮转的切片长度大。

lua_setallocf

[-0, +0, –]

void lua_setallocf (lua_State *L, lua_Alloc f, void *ud);

把指定状态机的分配器函数换成带上用户数据 udf

lua_setfield

[-1, +0, e ]

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

做一个等价于 t[k] = v 的操作, 这里 t 是给出的索引处的值, 而 v 是栈顶的那个值。

这个函数将把这个值弹出栈。 跟在 Lua 中一样,这个函数可能触发一个 "newindex" 事件的元方法 (参见§2.4)。

lua_setglobal

[-1, +0, e ]

void lua_setglobal (lua_State *L, const char *name);

从堆栈上弹出一个值,并将其设为全局变量 name 的新值。

lua_seti

[-1, +0, e ]

void lua_seti (lua_State *L, int index, lua_Integer n);

做一个等价于 t[n] = v 的操作, 这里 t 是给出的索引处的值, 而 v 是栈顶的那个值。

这个函数将把这个值弹出栈。 跟在 Lua 中一样,这个函数可能触发一个 "newindex" 事件的元方法 (参见§2.4)。

lua_setmetatable

[-1, +0, –]

void lua_setmetatable (lua_State *L, int index);

把一张表弹出栈,并将其设为给定索引处的值的元表。

lua_settable

[-2, +0, e ]

void lua_settable (lua_State *L, int index);

做一个等价于 t[k] = v 的操作, 这里 t 是给出的索引处的值, v 是栈顶的那个值, k 是栈顶之下的值。

这个函数会将键和值都弹出栈。 跟在 Lua 中一样,这个函数可能触发一个 "newindex" 事件的元方法 (参见§2.4)。

lua_settop

[-?, +?, –]

void lua_settop (lua_State *L, int index);

参数允许传入任何索引以及 0 。 它将把堆栈的栈顶设为这个索引。 如果新的栈顶比原来的大, 超出部分的新元素将被填为 nil 。 如果 index 为 0 , 把栈上所有元素移除。

lua_setuservalue

[-1, +0, –]

void lua_setuservalue (lua_State *L, int index);

从栈上弹出一个值并将其设为给定索引处用户数据的关联值。

lua_State

typedef struct lua_State lua_State;

一个不透明的结构, 它指向一条线程并间接(通过该线程)引用了整个 Lua 解释器的状态。 Lua 库是完全可重入的: 它没有任何全局变量。 状态机所有的信息都可以通过这个结构访问到。

这个结构的指针必须作为第一个参数传递给每一个库函数。 lua_newstate 是一个例外, 这个函数会从头创建一个 Lua 状态机。

lua_status

[-0, +0, –]

int lua_status (lua_State *L);

返回线程 L 的状态。

正常的线程状态是 0 ( LUA_OK )。 当线程用 lua_resume 执行完毕并抛出了一个错误时, 状态值是错误码。 如果线程被挂起,状态为 LUA_YIELD

你只能在状态为 LUA_OK 的线程中调用函数。 你可以延续一个状态为 LUA_OK 的线程 (用于开始新协程)或是状态为 LUA_YIELD 的线程 (用于延续协程)。

lua_stringtonumber

[-0, +1, –]

size_t lua_stringtonumber (lua_State *L, const char *s);

将一个零结尾的字符串 s 转换为一个数字, 将这个数字压栈,并返回字符串的总长度(即长度加一)。 转换的结果可能是整数也可能是浮点数, 这取决于 Lua 的转换语法(参见§3.1)。 这个字符串可以有前置和后置的空格以及符号。 如果字符串并非一个有效的数字,返回 0 并不把任何东西压栈。 (注意,这个结果可以当成一个布尔量使用,为真即转换成功。)

lua_toboolean

[-0, +0, –]

int lua_toboolean (lua_State *L, int index);

把给定索引处的 Lua 值转换为一个 C 中的布尔量( 0 或是 1 )。 和 Lua 中做的所有测试一样, lua_toboolean 会把任何不同于 falsenil 的值当作真返回; 否则就返回假。 (如果你想只接收真正的 boolean 值, 就需要使用 lua_isboolean 来测试值的类型。)

lua_tocfunction

[-0, +0, –]

lua_CFunction lua_tocfunction (lua_State *L, int index);

把给定索引处的 Lua 值转换为一个 C 函数。 这个值必须是一个 C 函数; 如果不是就返回 NULL

lua_tointeger

[-0, +0, –]

lua_Integer lua_tointeger (lua_State *L, int index);

等价于调用 lua_tointegerx , 其参数 isnumNULL

lua_tointegerx

[-0, +0, –]

lua_Integer lua_tointegerx (lua_State *L, int index, int *isnum);

将给定索引处的 Lua 值转换为带符号的整数类型 lua_Integer 。 这个 Lua 值必须是一个整数,或是一个可以被转换为整数 (参见§3.4.3)的数字或字符串; 否则, lua_tointegerx 返回 0 。

如果 isnum 不是 NULL*isnum 会被设为操作是否成功。

lua_tolstring

[-0, +0, e ]

const char *lua_tolstring (lua_State *L, int index, size_t *len);

把给定索引处的 Lua 值转换为一个 C 字符串。 如果 len 不为 NULL , 它还把字符串长度设到 *len 中。 这个 Lua 值必须是一个字符串或是一个数字; 否则返回返回 NULL 。 如果值是一个数字, lua_tolstring 还会 把堆栈中的那个值的实际类型转换为一个字符串 。 (当遍历一张表的时候, 若把 lua_tolstring 作用在键上, 这个转换有可能导致 lua_next 弄错。)

lua_tolstring 返回一个已对齐指针 指向 Lua 状态机中的字符串。 这个字符串总能保证 ( C 要求的)最后一个字符为零 ('/0') , 而且它允许在字符串内包含多个这样的零。

因为 Lua 中可能发生垃圾收集, 所以不保证 lua_tolstring 返回的指针, 在对应的值从堆栈中移除后依然有效。

lua_tonumber

[-0, +0, –]

lua_Number lua_tonumber (lua_State *L, int index);

等价于调用 lua_tonumberx , 其参数 isnumNULL

lua_tonumberx

[-0, +0, –]

lua_Number lua_tonumberx (lua_State *L, int index, int *isnum);

把给定索引处的 Lua 值转换为 lua_Number 这样一个 C 类型 (参见 lua_Number )。 这个 Lua 值必须是一个数字或是一个可转换为数字的字符串 (参见§3.4.3); 否则, lua_tonumberx 返回 0 。

如果 isnum 不是 NULL*isnum 会被设为操作是否成功。

lua_topointer

[-0, +0, –]

const void *lua_topointer (lua_State *L, int index);

把给定索引处的值转换为一般的 C 指针 ( void* ) 。 这个值可以是一个用户对象,表 ,线程或是一个函数; 否则, lua_topointer 返回 NULL 。 不同的对象有不同的指针。 不存在把指针再转回原有类型的方法。

这个函数通常只用于调试信息。

lua_tostring

[-0, +0, e ]

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

等价于调用 lua_tolstring , 其参数 lenNULL

lua_tothread

[-0, +0, –]

lua_State *lua_tothread (lua_State *L, int index);

把给定索引处的值转换为一个 Lua 线程 (表示为 lua_State* )。 这个值必须是一个线程; 否则函数返回 NULL

lua_touserdata

[-0, +0, –]

void *lua_touserdata (lua_State *L, int index);

如果给定索引处的值是一个完全用户数据, 函数返回其内存块的地址。 如果值是一个轻量用户数据, 那么就返回它表示的指针。 否则,返回 NULL

lua_type

[-0, +0, –]

int lua_type (lua_State *L, int index);

返回给定有效索引处值的类型, 当索引无效(或无法访问)时则返回 LUA_TNONElua_type 返回的类型被编码为一些个在 lua.h 中定义的常量: LUA_TNILLUA_TNUMBERLUA_TBOOLEANLUA_TSTRINGLUA_TTABLELUA_TFUNCTIONLUA_TUSERDATALUA_TTHREADLUA_TLIGHTUSERDATA

lua_typename

[-0, +0, –]

const char *lua_typename (lua_State *L, int tp);

返回 tp 表示的类型名, 这个 tp 必须是 lua_type 可能返回的值中之一。

lua_Unsigned

typedef ... lua_Unsigned;

lua_Integer 的无符号版本。

lua_upvalueindex

[-0, +0, –]

int lua_upvalueindex (int i);

返回当前运行的函数(参见§4.4)的第 i 个上值的伪索引。

lua_version

[-0, +0, v ]

const lua_Number *lua_version (lua_State *L);

返回保存在 Lua 内核中储存的版本数字的地址。 当调用时传入一个合法的 lua_State , 返回创建该状态机时的版本地址。 如果用 NULL 调用, 返回调用者的版本地址。

lua_Writer

typedef int (*lua_Writer) (lua_State *L,                            const void* p,                            size_t sz,                            void* ud);

lua_dump 用到的写入器函数。 每次 lua_dump 产生了一段新的代码块, 它都会调用写入器。 传入要写入的缓冲区 ( p ) 和它的尺寸 ( sz ) , 以及传给 lua_dump 的参数 data

写入器会返回一个错误码: 0 表示没有错误; 别的值均表示一个错误, 并且会让 lua_dump 停止再次调用写入器。

lua_xmove

[-?, +?, –]

void lua_xmove (lua_State *from, lua_State *to, int n);

交换同一个状态机下不同线程中的值。

这个函数会从 from 的栈上弹出 n 个值, 然后把它们压入 to 的栈上。

lua_yield

[-?, +?, e ]

int lua_yield (lua_State *L, int nresults);

这个函数等价于调用 lua_yieldk , 不同的是不提供延续函数(参见§4.7)。 因此,当线程被延续,线程会继续运行调用 lua_yield 函数的函数。

lua_yieldk

[-?, +?, e ]

int lua_yieldk (lua_State *L,                 int nresults,                 lua_KContext ctx,                 lua_KFunction k);

让出协程(线程)。

当 C 函数调用了 lua_yieldk , 当前运行的协程会挂起, 启动这个线程的 lua_resume 调用返回。 参数 nresults 指栈上需返回给 lua_resume 的返回值的个数。

当协程再次被延续时, Lua 调用延续函数 k 继续运行被挂起(参见§4.7)的 C 函数。 延续函数会从前一个函数中接收到相同的栈, 栈中的 n 个返回值被移除而压入了从 lua_resume 传入的参数。 此外,延续函数还会收到传给 lua_yieldk 的参数 ctx

通常,这个函数不会返回; 当协程一次次延续,将从延续函数继续运行。 然而,有一个例外: 当这个函数从一个逐行运行的钩子函数(参见§4.9) 中调用时, lua_yieldk 不可以提供延续函数。 (也就是类似 lua_yield 的形式), 而此时,钩子函数在调用完让出后将立刻返回。 Lua 会使协程让出,一旦协程再次被延续, 触发钩子的函数会继续正常运行。

当一个线程处于未提供延续函数的 C 调用中,调用它会抛出一个错误。 从并非用延续方式(例如:主线程)启动的线程中调用它也会这样。

4.9 – 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) */   int currentline;            /* (l) */   int linedefined;            /* (S) */   int lastlinedefined;        /* (S) */   unsigned char nups;         /* (u) number of upvalues */   unsigned char nparams;      /* (u) number of parameters */   char isvararg;              /* (u) */   char istailcall;            /* (t) */   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, call lua_getinfo .

The fields of lua_Debug have the following meaning:

  • source : the name of the chunk that created the function. If source starts with a ' @ ', it means that the function was defined in a file where the file name follows the ' @ '. If source starts with a ' = ', the remainder of its contents describe the source in a user-dependent manner. Otherwise, the function was defined in a string where source is that string.
  • short_src : a "printable" version of source , to be used in error messages.
  • linedefined : the line number where the definition of the function starts.
  • lastlinedefined : the line number where the definition of the function ends.
  • what : the string "Lua" if the function is a Lua function, "C" if it is a C function, "main" if it is the main part of a chunk.
  • currentline : the current line where the given function is executing. When no line information is available, currentline is set to -1.
  • name : a reasonable name for the given function. Because functions in Lua are first-class values, they do not have a fixed name: some functions can be the value of multiple global variables, while others can be stored only in a table field. The lua_getinfo function checks how the function was called to find a suitable name. If it cannot find a name, then name is set to NULL .
  • namewhat : explains the name field. The value of namewhat can be "global" , "local" , "method" , "field" , "upvalue" , or "" (the empty string), according to how the function was called. (Lua uses the empty string when no other option seems to apply.)
  • istailcall : true if this function invocation was called by a tail call. In this case, the caller of this level is not in the stack.
  • nups : the number of upvalues of the function.
  • nparams : the number of fixed parameters of the function (always 0 for C functions).
  • isvararg : true if the function is a vararg function (always true for C functions).

lua_gethook

[-0, +0, –]

lua_Hook lua_gethook (lua_State *L);

Returns the current hook function.

lua_gethookcount

[-0, +0, –]

int lua_gethookcount (lua_State *L);

Returns the current hook count.

lua_gethookmask

[-0, +0, –]

int lua_gethookmask (lua_State *L);

Returns the current hook mask.

lua_getinfo

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

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

Gets information about a specific function or function invocation.

To get information about a function invocation, the parameter ar must be a valid activation record that was filled by a previous call to lua_getstack or given as argument to a hook (see lua_Hook ).

To get information about a function you push it onto the stack and start the what string with the character ' > '. (In that case, lua_getinfo pops the function from the top of the stack.) For instance, to know in which line a function f was defined, you can write the following code:

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

Each character in the string what selects some fields of the structure ar to be filled or a value to be pushed on the stack:

  • ' n ': fills in the field name and namewhat ;
  • ' S ': fills in the fields source , short_src , linedefined , lastlinedefined , and what ;
  • ' l ': fills in the field currentline ;
  • ' t ': fills in the field istailcall ;
  • ' u ': fills in the fields nups , nparams , and isvararg ;
  • ' f ': pushes onto the stack the function that is running at the given level;
  • ' L ': pushes onto the stack a table whose indices are the numbers of the lines that are valid on the function. (A valid line is a line with some associated code, that is, a line where you can put a break point. Non-valid lines include empty lines and comments.)

    If this option is given together with option ' f ', its table is pushed after the function.

This function returns 0 on error (for instance, an invalid option in what ).

lua_getlocal

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

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

Gets information about a local variable of a given activation record or a given function.

In the first case, the parameter ar must be a valid activation record that was filled by a previous call to lua_getstack or given as argument to a hook (see lua_Hook ). The index n selects which local variable to inspect; see debug.getlocal for details about variable indices and names.

lua_getlocal pushes the variable's value onto the stack and returns its name.

In the second case, ar must be NULL and the function to be inspected must be at the top of the stack. In this case, only parameters of Lua functions are visible (as there is no information about what variables are active) and no values are pushed onto the stack.

Returns NULL (and pushes nothing) when the index is greater than the number of active local variables.

lua_getstack

[-0, +0, –]

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

Gets information about the interpreter runtime stack.

This function fills parts of a lua_Debug structure with an identification of the activation record of the function executing at a given level. Level 0 is the current running function, whereas level n+1 is the function that has called level n (except for tail calls, which do not count on the stack). When there are no errors, lua_getstack returns 1; when called with a level greater than the stack depth, it returns 0.

lua_getupvalue

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

const char *lua_getupvalue (lua_State *L, int funcindex, int n);

Gets information about a closure's upvalue. (For Lua functions, upvalues are the external local variables that the function uses, and that are consequently included in its closure.) lua_getupvalue gets the index n of an upvalue, pushes the upvalue's value onto the stack, and returns its name. funcindex points to the closure in the stack. (Upvalues have no particular order, as they are active through the whole function. So, they are numbered in an arbitrary order.)

Returns NULL (and pushes nothing) when the index is greater than the number of upvalues. For C functions, this function uses the empty string "" as a name for all upvalues.

lua_Hook

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

Type for debugging hook functions.

Whenever a hook is called, its ar argument has its field event set to the specific event that triggered the hook. Lua identifies these events with the following constants: LUA_HOOKCALL , LUA_HOOKRET , LUA_HOOKTAILCALL , LUA_HOOKLINE , and LUA_HOOKCOUNT . Moreover, for line events, the field currentline is also set. To get the value of any other field in ar , the hook must call lua_getinfo .

For call events, event can be LUA_HOOKCALL , the normal value, or LUA_HOOKTAILCALL , for a tail call; in this case, there will be no corresponding return event.

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 and they cannot yield any value; to yield a hook function must finish its execution calling lua_yield with nresults equal to zero.

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:

  • The call hook: is called when the interpreter calls a function. The hook is called just after Lua enters the new function, before the function gets its arguments.
  • The return hook: is called when the interpreter returns from a function. The hook is called just before Lua leaves the function. There is no standard way to access the values to be returned by the function.
  • The line hook: is called when the interpreter is about to start the execution of a new line of code, or when it jumps back in the code (even to the same line). (This event only happens while Lua is executing a Lua function.)
  • The count hook: is called after the interpreter executes every count instructions. (This event only happens while Lua is executing a Lua function.)

A hook is 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. Parameters ar and n are as in lua_getlocal (see lua_getlocal ). lua_setlocal assigns the value at 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.

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 at the top of the stack to the upvalue and returns its name. It also pops the value from the stack. Parameters funcindex and n are as in the lua_getupvalue (see lua_getupvalue ).

Returns NULL (and pops nothing) when the index is greater than the number of upvalues.

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 . Parameters funcindex and n are as in the lua_getupvalue (see lua_getupvalue ) (but n cannot be greater than the number of upvalues).

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

lua_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 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

[-?, +?, e ]

void luaL_addchar (luaL_Buffer *B, char c);

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

luaL_addlstring

[-?, +?, e ]

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

[-?, +?, e ]

void luaL_addsize (luaL_Buffer *B, size_t n);

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

luaL_addstring

[-?, +?, e ]

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

[-1, +?, e ]

void luaL_addvalue (luaL_Buffer *B);

Adds the value at 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_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:

  • First declare a variable b of type luaL_Buffer .
  • Then initialize it with a call luaL_buffinit(L, &b) .
  • Then add string pieces to the buffer calling any of the luaL_add* functions.
  • Finish by calling luaL_pushresult(&b) . This call leaves the final string on the top of the stack.

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

  • First declare a variable b of type luaL_Buffer .
  • Then initialize it and preallocate a space of size sz with a call luaL_buffinitsize(L, &b, sz) .
  • Then copy the string into that space.
  • Finish by calling luaL_pushresultsize(&b, sz) , where sz is the total size of the resulting string copied into that space.

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_buffinit

[-0, +0, –]

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

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

luaL_buffinitsize

[-?, +?, e ]

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

Equivalent to the sequence luaL_buffinit , luaL_prepbuffsize .

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 cast to a lua_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 *l 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.

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 address (see lua_touserdata ).

luaL_checkversion

[-0, +0, –]

void luaL_checkversion (lua_State *L);

Checks whether the core running the call, the core that created the Lua state, and the code making the call are all using the same version of Lua. Also checks whether the core running the call and the core that created the Lua state are using the same address space.

luaL_dofile

[-0, +?, e ]

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 false if there are no errors or true in case of errors.

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 false if there are no errors or true 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, e ]

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), e ]

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), e ]

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

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

Pushes onto the stack the metatable associated with name tname in the registry (see luaL_newmetatable ). If there is no metatable associated with tname , returns false and pushes nil .

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

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

Creates a copy of string s by 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 only can 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 function lua_load .

luaL_loadfile

[-0, +1, e ]

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

Equivalent to luaL_loadfilex with mode equal to NULL .

luaL_loadfilex

[-0, +1, e ]

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 function lua_load .

This function returns the same results as lua_load , but it has an extra error code LUA_ERRFILE if it cannot open/read the file or the file has a wrong mode.

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_newlib

[-0, +1, e ]

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

Creates a new table and registers there the functions in 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, e ]

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

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. (The entry __name is used by some error-reporting functions.)

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

luaL_newstate

[-0, +0, –]

lua_State *luaL_newstate (void);

Creates a new Lua state. It calls lua_newstate with an allocator based on the standard C realloc function and then sets a panic function (see§4.6) that prints an error message to the standard error output in case of fatal errors.

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

luaL_openlibs

[-0, +0, e ]

void luaL_openlibs (lua_State *L);

Opens all standard Lua libraries into the given state.

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 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 the position *l with the result's length.

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

[-?, +?, e ]

char *luaL_prepbuffer (luaL_Buffer *B);

Equivalent to luaL_prepbuffsize with the predefined size LUAL_BUFFERSIZE .

luaL_prepbuffsize

[-?, +?, e ]

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_pushresult

[-?, +1, e ]

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

void luaL_pushresultsize (luaL_Buffer *B, size_t sz);

Equivalent to the sequence luaL_addsize , luaL_pushresult .

luaL_ref

[-1, +0, e ]

int luaL_ref (lua_State *L, int t);

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

A reference is a unique integer key. As long as you do not manually add integer keys into table t , luaL_ref ensures the uniqueness of the key it returns. You can retrieve an object referred by reference r by calling lua_rawgeti(L, t, r) . Function luaL_unref frees a reference and its associated object.

If the object at 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 modname is not already present in package.loaded , calls function openf with string modname as an argument and sets the call result in package.loaded[modname] , as if that function has been called through require .

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

Leaves a copy of the module on the stack.

luaL_setfuncs

[-nup, +0, e ]

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 sharing nup upvalues, which must be previously pushed on the stack on top of the library table. These values are popped from the stack after the registration.

luaL_setmetatable

[-0, +0, –]

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

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

luaL_Stream

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

The standard representation for file handles, which is 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. Field f points to the corresponding C stream (or it can be NULL to indicate an incompletely created handle). 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 true (in case of success) or nil plus an error message (in case of error). Once Lua calls this field, the field value is changed to NULL to signal that the handle is closed.

luaL_testudata

[-0, +0, e ]

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. 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, e ]

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_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 reference ref from the table at index t (see luaL_ref ). The entry is removed from the table, so that the referred object can be collected. The reference ref is also freed to be used again.

If ref is LUA_NOREF or LUA_REFNIL , luaL_unref does nothing.

luaL_where

[-0, +1, e ]

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 – Standard Libraries

The standard Lua libraries provide useful functions that are implemented directly 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 are quite useful or have critical performance requirements that 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. Currently, Lua has the following standard libraries:

  • basic library (§6.1);
  • coroutine library (§6.2);
  • package library (§6.3);
  • string manipulation (§6.4);
  • basic UTF-8 support (§6.5);
  • table manipulation (§6.6);
  • mathematical functions (§6.7) (sin, log, etc.);
  • input and output (§6.8);
  • operating system facilities (§6.9);
  • debug facilities (§6.10).

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

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

6.1 – Basic Functions

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

assert (v [, message])

Calls 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 :

  • " collect ": performs a full garbage-collection cycle. This is the default option.
  • " stop ": stops automatic execution of the garbage collector. The collector will run only when explicitly invoked, until a call to restart it.
  • " restart ": restarts automatic execution of the garbage collector.
  • " count ": returns the total memory in use by Lua in Kbytes. The value has a fractional part, so that it multiplied by 1024 gives the exact number of bytes in use by Lua (except for overflows).
  • " step ": performs a garbage-collection step. The step "size" is controlled by arg . With a zero value, the collector will perform one basic (indivisible) step. For non-zero values, the collector will perform as if that amount of memory (in KBytes) had been allocated by Lua. Returns true if the step finished a collection cycle.
  • " setpause ": sets arg as the new value for the pause of the collector (see§2.5). Returns the previous value for pause .
  • " setstepmul ": sets arg as the new value for the step multiplier of the collector (see§2.5). Returns the previous value for step .
  • " isrunning ": returns a boolean that tells whether the collector is running (i.e., not stopped).

dofile ([filename])

Opens the named file and executes its contents as a Lua chunk. When called without arguments, dofile executes the contents of the standard input ( stdin ). Returns all values returned by the chunk. In case of errors, dofile propagates the error to its caller (that is, dofile

does not run in protected mode).

error (message [, level])

Terminates the last protected function called and returns message as the error object. Function error

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 table 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 nil value.

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, returns the compiled chunk as a function; otherwise, returns nil plus the error message.

If the resulting function has upvalues, the 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 . (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.) 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.9). 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.

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. 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 numeric order, use a numerical for .)

The behavior of next is undefined if, during the traversal, you assign any value to a non-existent field in the table. You may however modify existing fields. In particular, you may clear existing fields.

pairs (t)

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

Otherwise, returns three values: the next function, the table t , and nil , 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 the caveats of modifying the table during its traversal.

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

Calls 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 message.

print (···)

Receives any number of arguments and prints their values to stdout , using the tostring function to convert each argument to a string. 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 any metamethod. Returns a boolean.

rawget (table, index)

Gets the real value of table[index] , without invoking any metamethod. 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 any metamethod. Returns an integer.

rawset (table, index, value)

Sets the real value of table[index] to value , without invoking any metamethod. 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. (You cannot change the metatable of other types from Lua, only from C.) 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 .

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

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

tostring (v)

Receives a value of any type and converts it to a string in a human-readable format. Floats always produce strings with some floating-point indication (either a decimal dot or an exponent). (For complete control of how numbers are converted, use string.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.

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 current interpreter version. The current value of this variable is " Lua 5.3

".

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

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

6.2 – Coroutine Manipulation

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

coroutine.create (f)

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

coroutine.isyieldable ()

Returns true when the running coroutine can yield.

A running 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 coroutine co , as a string: "running" , if the coroutine is running (that is, it called status ); "suspended" , if the coroutine is suspended in a call to yield , or if it has not started running yet; "normal" if the coroutine is active but not running (that is, it has resumed another coroutine); and "dead" if the coroutine has finished its body function, or if it has stopped with an error.

coroutine.wrap (f)

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

coroutine.yield (···)

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

6.3 – Modules

The package library provides basic facilities for loading modules in Lua. It exports one function directly in the global environment: require . Everything else is exported in a 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] . Otherwise, it tries to find a loader for the module.

To find a loader, require is guided by the package.searchers sequence. By changing this sequence, 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 dependent on how it got the loader. (If the loader came from a file, this extra value is the file name.) 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] .

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:

  • The first line is the directory separator string. Default is ' / ' for Windows and ' / ' for all other systems.
  • The second line is the character that separates templates in a path. Default is ' ; '.
  • The third line is the string that marks the substitution points in a template. Default is ' ? '.
  • The fourth line is a string that, in a path in Windows, is replaced by the executable's directory. Default is ' ! '.
  • The fifth line is a mark to ignore all text after it when building the luaopen_ function name. Default is ' - '.

package.cpath

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

Lua initializes the C path package.cpath in the same way it initializes the Lua path package.path , using the environment variable LUA_CPATH_5_3 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 .

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 function is not supported by Standard C. As such, it is only available on some platforms (Windows, Linux, Mac OS X, Solaris, BSD, plus other Unix systems that support the dlfcn standard).

package.path

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

At start-up, Lua initializes this variable with the value of the environment variable LUA_PATH_5_3 or the environment variable LUA_PATH or with a default path defined in luaconf.h , if those environment variables are not defined. Any " ;; " 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 .

package.searchers

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

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

Lua initializes this table with four 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 name where the module was found, as returned by package.searchpath . The first searcher returns no extra value.

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 nil plus an error message if none succeeds. (This error message lists all file names it tried to open.)

6.4 – String Manipulation

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

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

The string library assumes one-byte character encodings.

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

Returns the internal numerical codes of the characters s[i] , s[i+1] , ..., s[j] . The default value for i is 1; the default value for j is  i . These indices are corrected following the same rules of function string.sub

.

Numerical codes are not necessarily portable across platforms.

string.char (···)

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

Numerical 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 is created without debug information about the function (local variable names, lines, etc.).

Functions with upvalues have only their number of upvalues saved. When (re)loaded, those upvalues receive fresh instances containing nil . (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.4.1) in the string s . If it finds a match, then find returns the indices of  s where this occurrence starts and ends; otherwise, it returns nil . A third, optional numerical argument init specifies where to start the search; its default value is 1 and can be negative. A value of 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. Note that if plain is given, then init must be given as well.

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

string.format (formatstring, ···)

Returns a formatted version of its variable number of arguments following the description given in its first argument (which must be a string). The format string follows the same rules as the ISO C function sprintf . The only differences are that the options/modifiers * , h , L , l , n , and p are not supported and that there is an extra option, q . The q option formats a string 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"

Options A and a (when available), E , e , f , G , and g all expect a number as argument. Options c , d , i , o , u , X , and x expect an integer. Option q expects a string; option s expects a string without embedded zeros. If the argument to option s is not a string, it is converted to one following the same rules of tostring .

string.gmatch (s, pattern)

Returns an iterator function that, each time it is called, returns the next captures from pattern (see§6.4.1) over the string s . If pattern

specifies no captures, then the whole match is produced in each call.

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.4.1) have been replaced by a replacement string specified by repl , which can be a string, a table, or a function. gsub also returns, as its second value, the total number of matches that occurred. The name gsub comes from Global SUBstitution

.

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.3"}  x = string.gsub("$name-$version.tar.gz", "%$(%w+)", t)  --> x="lua-5.3.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 pattern (see§6.4.1) in the string s . If it finds one, then match returns the captures from the pattern; otherwise it returns nil . If pattern specifies no captures, then the whole match is returned. A third, optional numerical 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. packed (that is, serialized in binary form) according to the format string fmt (see§6.4.2).

string.packsize (fmt)

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

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

string.reverse (s)

Returns a string that is the string s

reversed.

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

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

.

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.4.2). An optional pos marks where to start reading in s (default is 1). After the read values, this function also returns the index of the first unread byte in s .

string.upper (s)

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

6.4.1 – Patterns

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

Character Class:

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

  • x : (where x is not one of the magic characters ^$()%.[]*+-? ) represents the character x itself.
  • . : (a dot) represents all characters.
  • %a : represents all letters.
  • %c : represents all control characters.
  • %d : represents all digits.
  • %g : represents all printable characters except space.
  • %l : represents all lowercase letters.
  • %p : represents all punctuation characters.
  • %s : represents all space characters.
  • %u : represents all uppercase letters.
  • %w : represents all alphanumeric characters.
  • %x : represents all hexadecimal digits.
  • %x : (where x is any non-alphanumeric character) represents the character x . This is the standard way to escape the magic characters. Any non-alphanumeric character (including all punctuations, even the non-magical) can be preceded by a ' % ' when used to represent itself in a pattern.
  • [set] : represents the class which is the union of all characters in set . A range of characters can be specified by separating the end characters of the range, in ascending order, with a ' - '. All classes % x described above can also be used as components in set . All other characters in set represent themselves. For example, [%w_] (or [_%w] ) represents all alphanumeric characters plus the underscore, [0-7] represents the octal digits, and [0-7%l%-] represents the octal digits plus the lowercase letters plus the ' - ' character.

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

  • [^set] : represents the complement of set , where set is interpreted as above.

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

  • a single character class, which matches any single character in the class;
  • a single character class followed by ' * ', which matches zero or more repetitions of characters in the class. These repetition items will always match the longest possible sequence;
  • a single character class followed by ' + ', which matches one or more repetitions of characters in the class. These repetition items will always match the longest possible sequence;
  • a single character class followed by ' - ', which also matches zero or more repetitions of characters in the class. Unlike ' * ', these repetition items will always match the shortest possible sequence;
  • a single character class followed by ' ? ', which matches zero or one occurrence of a character in the class. It always matches one occurrence if possible;
  • %n , for n between 1 and 9; such item matches a substring equal to the n -th captured string (see below);
  • %bxy , where x and y are two distinct characters; such item matches strings that start with  x , end with  y , and where the x and y are balanced . This means that, if one reads the string from left to right, counting +1 for an x and -1 for a y , the ending y is the first y where the count reaches 0. For instance, the item %b() matches expressions with balanced parentheses.
  • %f[set] , a frontier pattern ; such item matches an empty string at any position such that the next character belongs to set and the previous character does not belong to set . The set set is interpreted as previously described. The beginning and the end of the subject are handled as if they were the character ' /0 '.

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

6.4.2 – Format Strings for Pack and Unpack

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

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

  • < : sets little endian
  • > : sets big endian
  • = : sets native endian
  • ![n] : sets maximum alignment to n (default is native alignment)
  • b : a signed byte ( char )
  • B : an unsigned byte ( char )
  • h : a signed short (native size)
  • H : an unsigned short (native size)
  • l : a signed long (native size)
  • L : an unsigned long (native size)
  • j : a lua_Integer
  • J : a lua_Unsigned
  • T : a size_t (native size)
  • i[n] : a signed int with n bytes (default is native size)
  • I[n] : an unsigned int with n bytes (default is native size)
  • f : a float (native size)
  • d : a double (native size)
  • n : a lua_Number
  • cn : a fixed-sized string with n bytes
  • z : a zero-terminated string
  • s[n] : a string preceded by its length coded as an unsigned integer with n bytes (default is a size_t )
  • x : one byte of padding
  • Xop : an empty item that aligns according to option op (which is otherwise ignored)
  • ' ': (empty space) ignored

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

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.

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

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.5 – 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.

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-/xF4][/x80-/xBF]* " (see§6.4.1

), which matches exactly one UTF-8 byte sequence, assuming that the subject is a valid UTF-8 string.

utf8.codes (s)

Returns values so that the construction

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

will iterate over all 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]])

Returns the codepoints (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]])

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 a false value plus the position of the first invalid byte.

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

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

.

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

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

6.6 – 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, the table must be a proper sequence or have a __len metamethod (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.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 list t .

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

Moves elements from table a1 to table a2 . This function performs 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. Index f must be positive.

table.pack (···)

Returns a new table with all parameters stored into keys 1, 2, etc. and with a field " n " with the total number of parameters. Note that the resulting table may not be a sequence.

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 ; in those cases, the function erases the element list[pos] .

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

table.sort (list [, comp])

Sorts 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 not comp(list[i+1],list[i]) will be true after the sort). If comp is not given, then the standard Lua operator < is used instead.

The sort algorithm is not stable; that is, 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.7 – Mathematical Functions

This library provides basic mathematical functions. It provides all its functions and constants inside the table math . Functions with the annotation " integer/float " give integer results for integer arguments and float results for float (or mixed) arguments. 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 absolute value of 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), but uses the signs of both parameters 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 larger 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 e x (where e is the base of natural logarithms).

math.floor (x)

Returns the largest integral value smaller 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.huge

The float value HUGE_VAL , a value larger than any other numerical value.

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 < . (integer/float)

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 < . (integer/float)

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 value m-n cannot be negative and must fit in a Lua integer.) The call math.random(n) is equivalent to math.random(1,n) .

This function is an interface to the underling pseudo-random generator function provided by C. No guarantees can be given for its statistical properties.

math.randomseed (x)

Sets x as the "seed" for the pseudo-random generator: equal seeds produce equal sequences of numbers.

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

math.type (x)

Returns " integer " if x is an integer, " float " if it is a float, or nil if x is not a number.

math.ult (m, n)

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

6.8 – Input and Output Facilities

The I/O library provides two different styles for file manipulation. The first one uses implicit file handles; that is, there are operations to set a default input file and a default output file, and all input/output operations are 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 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 nil on failure (plus an error message as a second result and a system-dependent error code as a third result) and some value different from nil 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 parameters, 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 detects the end of file, it returns no values (to finish the loop) and automatically closes the file.

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 it does not close the file when the loop ends.

In case of errors 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 . It returns a new file handle, or, in case of errors, nil plus an error message.

The mode string can be any of the following:

  • " r ": read mode (the default);
  • " w ": write mode;
  • " a ": append mode;
  • " r+ ": update mode, all previous data is preserved;
  • " w+ ": update mode, all previous data is erased;
  • " a+ ": append update mode, previous data is preserved, writing is only allowed at the end of file.

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

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

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

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 nil if it cannot read data with the specified format. (In this latter case, the function does not read subsequent formats.) When called without formats, it uses a default format that reads the next line (see below).

The available formats are

  • " n ": reads a numeral and returns it as a float or an integer, following the lexical conventions of Lua. (The numeral may have leading spaces and a sign.) This format always reads the longest input sequence that is a valid prefix for a number; if that prefix does not form a valid number (e.g., an empty string, " 0x ", or " 3.4e- "), it is discarded and the function returns nil .
  • " i ": reads an integral number and returns it as an integer.
  • " a ": reads the whole file, starting at the current position. On end of file, it returns the empty string.
  • " l ": reads the next line skipping the end of line, returning nil on end of file. This is the default format.
  • " L ": reads the next line keeping the end-of-line character (if present), returning nil on end of file.
  • number : reads a string with up to this number of bytes, returning nil on end of file. If number is zero, it reads nothing and returns an empty string, or nil on end of file.

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:

  • " set ": base is position 0 (beginning of the file);
  • " cur ": base is current position;
  • " end ": base is end of file;

In case of success, seek returns the final file position, measured in bytes from the beginning of the file. If seek fails, it returns nil , 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 an output file. There are three available modes:

  • " no ": no buffering; the result of any output operation appears immediately.
  • " full ": full buffering; output operation is performed only when the buffer is full or when you explicitly flush the file (see io.flush ).
  • " line ": line buffering; output is buffered until a newline is output or there is any input from some special files (such as a terminal device).

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

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 nil plus a string describing the error.

6.9 – 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.

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 (four digits), month (1–12), day (1–31), hour (0–23), min (0–59), sec (0–61), wday (weekday, Sunday is 1), yday (day of the year), 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 .

When called without arguments, date returns a reasonable date and time representation that depends on the host system and on the current locale (that is, os.date() is equivalent to os.date("%c") ).

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 nil otherwise. After this first result the function returns a string plus a number, as follows:

  • " exit ": the command terminated normally; the following number is the exit status of the command.
  • " signal ": the command was terminated by a signal; the following number is the signal that terminated the command.

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, closes the Lua state before exiting.

os.getenv (varname)

Returns the value of the process environment variable varname , or nil 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 nil , plus a string describing the error and the error code.

os.rename (oldname, newname)

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

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 nil 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 time when called without arguments, or a time representing the 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 ). For a description of these fields, see the os.date function.

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 .

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.

On 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.10 – The Debug Library

This library provides the functionality of the debug interface (§4.9) 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.

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

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 on the stack); and so on. If f is a number larger than the number of active functions, then getinfo returns nil .

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

For instance, the expression debug.getinfo(1,"n").name returns a table with 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, temporaries, etc.

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. Negative indices refer to vararg parameters; -1 is the first vararg parameter. The function returns nil 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.5).

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 nil if there is no upvalue with the given index.

Variable names starting with ' ( ' (open parenthesis) represent variables with no known names (variables from chunks saved without debug information).

debug.getuservalue (u)

Returns the Lua value associated to u . If u is not a userdata, returns nil .

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

Sets the given function as a 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:

  • ' c ': the hook is called every time Lua calls a function;
  • ' r ': the hook is called every time Lua returns from a function;
  • ' l ': the hook is called every time Lua enters a new line of code.

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" (or "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 nil 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 nil if there is no upvalue with the given index. Otherwise, it returns the name of the upvalue.

debug.setuservalue (udata, value)

Sets the given value as the Lua value associated to the given udata . udata must be a full userdata.

Returns udata .

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

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

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, including the debug library. Its usage is:

lua [options] [script [args]]

The options are:

  • -e stat : executes string stat ;
  • -l mod : "requires" mod ;
  • -i : enters interactive mode after running script ;
  • -v : prints version information;
  • -E : ignores environment variables;
  • -- : stops handling options;
  • - : executes stdin as a file and stops handling options.

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 option -E , the interpreter checks for an environment variable LUA_INIT_5_3 (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 option -E , besides ignoring LUA_INIT , Lua also ignores the values of LUA_PATH and LUA_CPATH , setting the values of package.path and package.cpath with the default paths defined in luaconf.h .

All options are handled in order, except -i and -E . For instance, an invocation like

$ lua -e'a=1' -e 'print(a)' script.lua

will first set a to 1, then print the value of a , 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 parameters arg[1] , ···, arg[#arg] . (Like all chunks in Lua, the script is compiled as a vararg function.)

In interactive mode, Lua repeatedly prompts and waits for a line. After reading a line, Lua first try to interpret the line as an expression. If it succeeds, it prints its value. Otherwise, it interprets the line as a statement. If you write an incomplete statement, the interpreter waits for its completion by issuing a different prompt.

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 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, the standalone interpreter skips the first line of a 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.2 to Lua 5.3. 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.

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 not 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 – Changes in the Language

  • The main difference between Lua 5.2 and Lua 5.3 is the introduction of an integer subtype for numbers. Although this change should not affect "normal" computations, some computations (mainly those that involve some kind of overflow) can give different results.

    You can fix these differences by forcing a number to be a float (in Lua 5.2 all numbers were float), in particular writing constants with an ending .0 or using x = x + 0.0 to convert a variable. (This recommendation is only for a quick fix for an occasional incompatibility; it is not a general guideline for good programming. For good programming, use floats where you need floats and integers where you need integers.)

  • The conversion of a float to a string now adds a .0 suffix to the result if it looks like an integer. (For instance, the float 2.0 will be printed as 2.0 , not as

    .) You should always use an explicit format when you need a specific format for numbers.

    (Formally this is not an incompatibility, because Lua does not specify how numbers are formatted as strings, but some programs assumed a specific format.)

  • The generational mode for the garbage collector was removed. (It was an experimental feature in Lua 5.2.)

8.2 – Changes in the Libraries

  • The bit32 library has been deprecated. It is easy to require a compatible external library or, better yet, to replace its functions with appropriate bitwise operations. (Keep in mind that bit32 operates on 32-bit integers, while the bitwise operators in standard Lua operate on 64-bit integers.)
  • The Table library now respects metamethods for setting and getting elements.
  • The ipairs iterator now respects metamethods and its __ipairs metamethod has been deprecated.
  • Option names in io.read do not have a starting ' * ' anymore. For compatibility, Lua will continue to ignore this character.
  • The following functions were deprecated in the mathematical library: atan2 , cosh , sinh , tanh , pow , frexp , and ldexp . You can replace math.pow(x,y) with x^y ; you can replace math.atan2 with math.atan , which now accepts one or two parameters; you can replace math.ldexp(x,exp) with x * 2.0^exp . For the other operations, you can either use an external library or implement them in Lua.
  • The searcher for C loaders used by require changed the way it handles versioned names. Now, the version should come after the module name (as is usual in most other tools). For compatibility, that searcher still tries the old format if it cannot find an open function according to the new style. (Lua 5.2 already worked that way, but it did not document the change.)

8.3 – Changes in the API

  • Continuation functions now receive as parameters what they needed to get through lua_getctx , so lua_getctx has been removed. Adapt your code accordingly.
  • Function lua_dump has an extra parameter, strip . Use 0 as the value of this parameter to get the old behavior.
  • Functions to inject/project unsigned integers ( lua_pushunsigned , lua_tounsigned , lua_tounsignedx , luaL_checkunsigned , luaL_optunsigned ) were deprecated. Use their signed equivalents with a type cast.
  • Macros to project non-default integer types ( luaL_checkint , luaL_optint , luaL_checklong , luaL_optlong ) were deprecated. Use their equivalent over lua_Integer with a type cast (or, when possible, use lua_Integer in your code).

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 |     local namelist [‘=’ explist]    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 [‘,’ ‘...’] | ‘...’   tableconstructor ::= ‘{’ [fieldlist] ‘}’   fieldlist ::= field {fieldsep field} [fieldsep]   field ::= ‘[’ exp ‘]’ ‘=’ exp | Name ‘=’ exp | exp   fieldsep ::= ‘,’ | ‘;’   binop ::=  ‘+’ | ‘-’ | ‘*’ | ‘/’ | ‘//’ | ‘^’ | ‘%’ |     ‘&’ | ‘~’ | ‘|’ | ‘>>’ | ‘<<’ | ‘..’ |     ‘<’ | ‘<=’ | ‘>’ | ‘>=’ | ‘==’ | ‘~=’ |     and | or   unop ::= ‘-’ | not | ‘#’ | ‘~
正文到此结束
Loading...