Extension:Scribunto/Lua reference manual/zh

此手册记载的文档，它用于MediaWiki的扩展. 部分内容取自Lua 5.1参考手册，其许可协议为MIT许可证.



入门
在已启用Scribunto的MediaWiki wiki上，以“Module:”前缀为标题创建一个页面，例如“Module:Bananas”. 进入该新页面，复制下列文本：

保存之后，另一个非模块的页面将会写入：

除了你应该将“Bananas”替换成你需要调用的模块. 这将会使“hello”函数被模块调用. 将会被函数输出的结果替换，那么，“Hello, world!”

从模板的内容调用Lua代码确实是一个好办法. 这意味着从调用页面的角度来说，语法不依赖与模板逻辑是否被Lua或者维基文本执行. 这也避免了把复杂语法加到wiki内容页面中.

模块结构
模块本身必须返回一个包含能被 调用的函数的表（table）. 一般来说，如上所示，先声明一个局部变量表，函数被写在这个表中，而且最终的模块代码中，返回（return）这个表.

若是没有加到这个表中的函数，无论是局部（变量）还是全局（变量），都不能被 关联，但是局部变量可能会被其他的用 加载的模块关联. 对于模块来说，最好将所有的函数和变量声明为局部变量.

从维基文本关联参数
被 调用函数时，会将框架项目（frame object）作为调用函数时的参数（参数只有一个）. 要关联被 通过的函数，代码通常会使用框架项目的 表. 也可以关联被包含 的模板参数，方法是使用 frame:getParent 然后关联到框架的.

框架项目也用来关联特定情况下的维基文本解析器，例如调用解析器函数、扩展模板以及展开任意的（含模板或解析器函数的）维基文本字符串.

返回文本
模块函数通常返回单个的字符串；无论返回什么值都会通过tostring转换，然后连接在一起. 这个字符串就是转化成维基文本代码 的结果.

在解析页面的这一点上，模板已经被展开，解析器函数和扩展标签都已经处理，而且预存的转换（例如签名的扩展以及pipe trick）都已经完成. 因此，模块不能在输出文本中使用这些特性. 例如，如果一个模块返回 ，页面就会是“你好，世界！ ”.

另一方面，替换引用会在处理过程的早期就被处理，所以带有 会尝试替换后的处理内容. 因为失败的替换引用会保持为维基文本，它们都会被下一次编辑处理. 这得要避免.

模块文档
Scruibunto允许模块可以被自动关联的模块维基文本页面关联文档；默认情况下，模块的“/doc”子页面是用来作为文档，并且会在模块页面的代码顶部显示其内容. 例如，“模块:Bananas”的文档页面就是“模块:Bananas/doc”.

这也可以使用以下MediaWiki名字空间下的消息配置：


 * scribunto-doc-page-name（文档页面名称）：设置用来作文档页面的名称. 模块（除了模块:prefix）的名称会通过 . 如果在模块命名空间，这里的页面通常会视为维基文本而不是Lua代码，也不会被 使用. 模块的页面通常是“Module:$1/doc”这样的模块/doc子页面. 注意解析器函数等其他可扩展代码在这个消息中不被使用.
 * scribunto-doc-page-does-not-exist（文档页面不存在）：消息会在文档页面不存在时显示. 页面名称通常会通过 . 默认是空的.
 * scribunto-doc-page-show（文档页面显示）：当文档页面存在时，消息就会显示. 页面的名称通常会通过 . 默认是引用文档页面.
 * scribunto-doc-page-header（文档页面开头）：当显示文档页面本身时，会显示开头. 模块（包括模块:prefix）的开头会通过 而作为文档. 默认情况下会简单显示为斜体的表达句.

注意模块不可以被直接分类，也不可以直接添加跨维基链接. 这些应该放在文档页面里面的 标签中，当文档页面引用到模块页面时，它们就会应用于模块中.

变量名称
Lua中的名称（Names）（也叫标识符（identifiers））通常可以是任何字母、数字和下划线的字符串，但不可以以数字开头. 名称区分大小写；“foo”“Foo”和“FOO”都是不同的名称.

下列关键字是保留的，不能用作名称：



名字的开头一个下划线大写字母是留给内部Lua全局变量.

下面这些文本也属于保留字：



注释
注释在任何地方（除了字符串内）由 开始. 如果 紧接着开放的中括号，注释就会一直延伸到下一个中括号；否则注释会延伸到这一行的结尾.

）开始，延续到一行末尾. -- 多行的字符串和注释    可以被两层中括号括起来. --[=[ 像这样的注释可以紧随其他--注释. ]=] --[==[ 像这样的注释可以有其他的 --[===[ 修长的 --[=[注释]=] --跟随着 ]===] 多次，即使它们所有 --[[ 都没有用匹配的长括号分隔！ ]===] ]==]

数据类型
Lua是动态类型语言，意味着变量和函数值都不会有种类，只有值会有. 所有的值都有类型.

Lua有8个基本类型，然而只有6个是与Scribunto扩展相关. 函数会返回值的类型.

能够将值转化为字符串（string）. 能够将值转化为数字（number）（如果可能的话），而其他情况则会返回空值（nil）. 没有明确的函数能够将一个值转化为其他的数据类型.

凡是将与字符串（string）连接在一起的地方，数字（number）会自动转化为字符串. 使用计算符号时，字符串会由 自动转化为数字辨识. 当运算中需要将一个值作为布尔值（boolean）时，除了nil和false之外，所有的值都会视为true.

空值（nil）
“空值”是 的数据类型，用来表示这个值不存在.

空值不一定作为一个表（table）中的域名（key），而且表中未指定的域名其实就是nil值的域名.

当空值转化为字符串时，其结果会是“nil”；转化为布尔值（boolean）时，空值会被视为false.

布尔值（boolean）
布尔值就是 （真）和 （假）.

当布尔值转化为字符串时，结果就是“true”或者“false”.

不像很多其他语言，布尔值不会直接转化为数字. 而且只有false和nil作为布尔值时也会视为false；数字0和空字符串都是视为true.

字符串（string）
Lua字符串会视为一系列的8比特字节；这取决于应用程序以哪种特定的编码来解析.

字符串会记录在任何一组单双引号（ 或 ）中；就像JavaScript而不像PHP，这两者（指的单引号和双引号）无区别. 以下转义序列被辨识：


 * （响铃，字节7）
 * （退格，字节8）
 * （水平制表符，字节9）
 * （换行，字节10）
 * （纵向制表符，字节11）
 * （换页，字节12）
 * （回车，字节13）
 * （双引号，字节34）
 * （单引号，字节39）
 * （反斜线，字节92）

在字符串代码中直接换行，应该在前面加一个反斜线（\）. 字节也可以通过转义序列'\ddd'，这样ddd是0～255中的字节值. 使用转义序列来代替Unicode字符，则为UTF-8的单个编码字节必须要指定；总的来说，直接输入Unicode字符会更加简单.

字符串也可以用长括号定义. 长括号之间可以夹杂着0个或更多个等号（两边的等号要等量），例如 、 或. 开放的长括号必须被相应的闭合的长括号（或者说是结束标记）链接，例如 、 或者 .. 特殊情况下，开放的长括号紧跟着连续换行但未被包括的字符串，新一行只会持续到闭合长括号前. 由长括号定义的字符串不会处理转义序列.

注意，在转化为布尔值时，所有的字符串都会视为true（真）. 这不像其他的语言将空字符串视为false（假）.

数字（number）
Lua只有一种数字类型，就是典型的双精度浮点数. 在这种格式，-9007199254740992到9007199254740992之间的数都会准确表达，更大的小数将会受到舍入的误差.

数字可以用点（ ）来表示小数，例如. 数字也可以用不带空格的科学计数法，例如 、 或者. 也可以用16进制表示整数，方法就是以 开头，例如.

虽然NaN和正负无穷大都可以正确地储存、处理，但是Lua不提供相应的直接文字表示方法. 是正无穷大，相当于 ，此外，像 这样的除法就可以生成NaN.

重申一遍，在转化为布尔值时，任何数字都会被视为true. 这不像其他语言，数字0通常视为false. 数字在转化为字符串时，数字都会被视为有限小数和科学计数；NaN是 或者 ；无穷大就是 或.

表（table）
Lua的表是关联数组，很像PHP的数组和JavaScript的object.

表要用一对花括号创建. 空表是. 创建有多个域的表时，逗号和分号可以分隔表中的各个域. 表的内容可以用以下形式表示：


 * ，意思是键为表达式1，它与值表达式2匹配. 即表达式1的值是表达式2.
 * ，它等价于.
 * 大致相当于 ，在这里i是在这个表中从1开始排序的正整数. 如果最后一个字段和表达式有多个值，所有的值都会使用；否则只有第一个会保留.

表中的域用中括号关联，例如. 字符串键（key）同样也可以用作点来表示的名字，例如 就与 等价. 这样的用点表示域的方法也可以用来调用函数，例如 ，相当于 或者.

序列从1到N的所有正整数且没有比N更大的正整数，且非空值的表. 很多Lua函数仅按它的序列操作，忽略所有的非整数或小数的域名.

不像很多其他的语言（例如PHP或JavaScript），任何值（除了nil和NaN）都可以作为键，而且没有执行类型转换. 参看下面的示例：

类似地，任何非nil的值都可以在表中储存为值. 将表中存储nil相当于删除表中的对应的键，并且调用表中任何一个不存在的键都会返回nil.

注意，在Lua中，表从来不会复制出一个独立的新表；如果表作为一个参数传递到函数，那么函数能修改表中的键或值，这些变化在调用者（caller）的作用域中都会可见.

当转化为字符串时，结果通常是"table"（在Lua 5.3.1中），但使用 元方法时，转化为字符串的值就会重写. 作为布尔值时，即使是空的表也会视为真（true）.

函数（function）
Lua中的函数（又叫功能）是最好的（first-class）的值：它们可以匿名创建，作为参数传递，给变量赋值，等等.

函数通过 （“函数”的英文）关键字，并使用圆括号调用. 有一些语法糖可以用来命名函数，局部函数，并且可以作为表中的一个域值. 参看函数声明和函数调用.

Lua函数是闭包，这意味着它们维护对它们声明的范围的引用，并可以访问和操作该范围中的变量.

类似于表，如果函数一个函数被分配给另一个变量，或者作为参数传递给另一个函数，它仍然是相同的被调用的底层“函数对象”.

函数转化为字符串时，结果是"function"（在Lua 5.3.1中是如此）.

不支持的类型
用户数据（userdata）用来储存其他语言中的值；例如，一个用户数据可以用来储存C的指针或结构. 使用Scribunto运行环境不允许使用用户数据.

线程数据类型代表协同处理，在Scribunto的沙盒中不可用.

元表
每个表可能都关联一个被称为元表的表. 元表的每个域都被特定的操作符或函数调用，以使表发生不同的操作行为或回落到默认行为. 元表通过getmetatable方法获得，通过setmetatable方法设定.

如果需要关联至元方法，需要在元表里面调用rawget方法.

元表可以配置以下项目元素：
 * __index
 * 使用这个时， 会返回nil. 如果值是表的域，输出就会在表中重复，例如 （会调用表的元表的__index）.  如果这个域的值是函数，函数就会像 这样调用.  rawget函数会绕过这个元方法.


 * __newindex
 * 这个元方法用于将一个域名关联值一个表中，即 ，但是 会返回空值（nil）. 如果这个域的值是表，那么这个表就会重复赋值，例如 （会调用这个表的元表的__newindex）.  如果这个域的值是函数，那么函数就会像这样调用： .  rawset函数会绕过这个元方法.


 * __call
 * 将这个表作为函数调用时，就会使用这种元表， . 这个值必须是函数，像 这样调用.


 * __mode
 * 这用于使表保持弱引用（weak references）. 这个值一定是一个字符串.  默认情况下，任何一个值被作为表格中的键或值时是不会被垃圾回收的.  但如果元表域包含字母k，且没有弱引用，键会作为垃圾收集. 而且如果包含v则值有可能也会作为垃圾收集；其他的情况，对应的键和值都会从表中移除.  注意，如果在表作为元表之后改变了域，这个域的行为就会未定义.

其他元表项目包括：


 * __add†
 * __sub†
 * __mul†
 * __div†
 * __mod†
 * __pow†
 * __unm
 * __concat†
 * __eq‡
 * __lt‡
 * __le‡
 * __pairs
 * __ipairs
 * __metatable*
 * __tostring

† 对于二元运算符，Lua首先检查左边的变量的元表（若有），如果左边变量的元方法不存在则使用右边的元方法. ‡ 对于关系运算符，只有在同样的函数在两个变量的元表定义时，元表才会被使用. 不同的匿名函数，即使具有相同的主体和闭包，也不可能被认为是相同的. * __metatable会同时影响getmetatable和setmetatable

注意：在Lua中，所有的字符串都会共用一个单一的元表，__index会转到 表. 在Scribunto中，这个元表不允许被关联，也不能被 表引用；对模块可用的string表是一个副本.

变量
变量是储存值的地方. Lua有三种变量：全局（global）变量、局部（local）变量和表（table）中的域（field）.

名称分为全局和局部变量（或者是函数变量，是局部变量的一种）. 定义一个局部变量，可以使用关键词. 任何没有赋值的变量都会视为有nil值.

全局变量储存在叫做环境的Lua表中；这个表通常是作为全局变量 的值. 这个全局变量表也可以设置元表；__index和__newindex元方法都可以用于全局变量表，就像其他的表一样.

函数的环境可以使用getfenv函数关联，使用setfenv函数修改；在Scribunto中，这些函数如果全部可用，就会受到严重限制.

局部变量是词法性质的；参见局部变量定义了解详细信息.

表达式
表达式是有值的：常量（数字、字符串、布尔值（真假）、空）、匿名函数的声明、表构造函数、变量引用、函数调用、变量参数表达式、用括号括起来的表达式、一进制和二进制运算的表达式.

大多数表达式都有一个值；函数调用和变量参数表达式可以有任何数量个值. 注意用括号括一个函数调用或变量参数表达式只能保留第一个值，其他的值会失去.

表达式列表是逗号分隔的表达式列表. 除了最后一个表达式以外，所有的值都只能是一个值（如果表达式没有值，则丢弃附加值，或者使用nil）；最后一个表达式的所有值都包含在表达式列表的值中.

算数运算符
Lua支持以下常见的算数运算符：加减乘除、模运算、幂和相反数.

当所有操作值为数字或字符串时，即使用tonumber返回非nil时，这些操作符有他们通常的意义.

如果一个操作数是一个有合适的#Metatables的表，元方法就会被调用.

关系运算符
Lua的关系运算符是 、 、 、 、 和. 关系运算的结果一定是布尔值（boolean）.

等于号（ ）首先比较两个值的种类；如果两个值是不同的种类，结果为假（false）. 然后比较值：空值、布尔值、数字和字符串照常比较. 对于函数，则是看两个函数是否引用同一个准确的函数对象；像这样检测两个不同的（但作用相同的）匿名函数 一定会返回假（false）. 表也会默认像函数这样比较，但是可能会由于使用__eq元方法而改变结果.

不等号（ ）与等于号作用相反.

对于排序运算符，如果两者都是数字，或者两者都是字符串，则直接进行比较. 其次检查元方法：


 * 使用
 * 使用 如果可用，或者 可用，那么它等价于
 * 等价于
 * 等价于

如果必需的元方法不可用，会产生错误.

逻辑运算符
逻辑运算是 （与）、 （或）和 （非）. 在逻辑运算中，只有空值（nil）和falce被视为false，其他的都被视为true.

对于 ，如果左边的操作数被视为假，那么它就会被返回，将右边的操作数忽略；否则右边的操作数会被返回.

对于 ，如果左边的操作数视为真，那么它就会被返回，忽略右边的操作数；否则右边的操作数会被返回.

对于 ，其结果一定是布尔值（true或false）.

注意 和 short circuit. 例如， 只会调用 ，除非 不是在它的返回false或nil.

连接运算符
连接运算符就是两个点（dot），比如. 如果两个操作数都是数字或字符串，它们会被转化为字符串然后返回. 但是如果__concat元方法可用，就会使用这样的元方法. 如果它存在但无效，则会产生错误.

注意Lua的字符串不可以改变，而且Lua不提供任何的“字符串产生器”的排序，所以反复进行 会必须为每次迭代创建一个新字符串，并最终收集旧字符串. 如果许多字符串都需要连接，则使用string.format或将所有的字符串添加到一个序列然后最后使用table.concat.

长度运算符
长度运算符是 ，像 这样使用. 如果 是字符串，会返回字符串的比特数. 如果 是序列表，会返回序列的长度.

如果 是一个不是序列的表， 会返回能够使“a[n]不是nil而a[N+1]是nil”成立的值N，即使更高的索引不是nil值（在Lua 5.1如此）. 例如，

运算优先级
Lua的操作符优先级，从高到低为：


 * 1) not # - （负号）
 * 2) + - （减号）
 * 3) and
 * or
 * 1) and
 * or
 * 1) and
 * or

在同一级中，二元运算符会从左到右运算，例如 相当于. 幂运算和级联会从右往左，例如 相当于 >

函数调用
Lua的函数调用域其他的语言很类似：函数名称后面跟着被括号括起来的参数列表.

func( 表达式列表 )

和往常一样在Lua表达的列表，列表中的最后一个表达式可以提供多个参数值.

如果向函数传递的参数个数少于函数定义中的形参个数，则额外的形参将被赋值nil. 如果函数表达式含有比形参更多的参数，则多余的参数会被丢弃. 函数也可以接受可变个数的参数（也就是说，有时可以接受任意数量个参数），参见函数声明的细节.

Lua允许直接调用由函数返回的值，例如. 如果需要比变量访问更复杂的表达式来确定要调用的函数，则可以使用括号表达式来代替变量访问.

Lua的语法有两个常见的语法糖例子. 第一个是当一个表被当做对象使用，并且这个对象有一个函数被调用，那么语法

table:name( 表达式 )

完全等同于

table.name( 表, 表达式 )

第二种常见的情况就是Lua通过含有名称至值的映射的表作为函数唯一参数实施已命名的参数的工具（直截了当说，就是将一个由花括号分割的表作为唯一参数）. 这种情况下，包围着参数的括号可以省去. 如果将一个（由引号或中括号分割的）字符串作为调用函数时的唯一参数，那么包围着这个参数的括号也可以省去. 比如调用

func{ arg1 = exp, arg2 = exp } func"string"

等同于

func( { arg1 = exp, arg2 = exp } ) func( "string" )

它们也可以被组合使用. 以下使用是等价的：

table:name{ arg1 = exp, arg2 = exp } table.name( table, { arg1 = exp, arg2 = exp } )

函数声明
方法的定义语法如下：

function ( var-list ) block end

对于这个函数，变量列表中的所有变量都是局部的，这些变量带有着函数调用的表达式列表. 在这个代码段中，多余的局部变量会被忽略.

函数被调用时，代码段中的语句会在由参数列表创建与变量表对应的局部变量和指定值之后执行. 如果执行到返回语句，代码段就会退出，返回的值则会在表达式中的调用函数时被返回语句给予. 如果执行到代码段末尾，还没有返回语句，则函数调用返回的结果是0个值.

Lua函数是词法闭包. 一个常见的习惯用法是在函数声明的范围内声明“私有静态”变量作为局部变量. 比如，

函数可以声明接受可变数量的（即任何数量个）参数，通过将 作为变量列表的最后一项：

function ( var-list, ... ) 语句块（block） end

在这个块内，变量表达式 就可使用，结果会是函数调用中的所有额外值. 比如，

select函数就是用来作用于这些参数表达式的；特别地，是使用 而非 来数参数表达式有多少个，因为 不一定是序列.

Lua为将函数声明和赋值提供到变量中提供语法糖；参见函数声明语句的细节.

注意这个不会起效：

 local factorial = function ( n ) if n <= 2 then return n   else return n * factorial( n - 1 ) end end

因为这个函数声明是在局部变量赋值声明完成之前就处理好的，函数主体中的“factorial”会指向函数外（通常是未定义的）变量. 这个问题可以通过先声明一个局部变量然后再将它分配到后来的声明中，或者使用函数声明语句语法.

声明
语句是执行的基本单元：一个赋值、控制结构、函数调用、变量声明，等等.

代码块（chunk）是语句（statements）的序列，可以由分号分开. 一个代码块基本上被考虑为匿名函数的主体，所以它可以声明局部变量，接受参数，并返回值.

语句块（block）也是语句序列，就像一个代码块（chunk）. 语句块可以被分隔以创建单个语句（statement）：. 这些通常用来限制局部变量的作用范围，或者在另一个块的中间加入 或.

赋值
var-list是由逗号分隔的变量；表达式列表是由逗号分隔的一组一个或多个表达式. 所有的表达式都会在赋值之前被求值，所以 会交换 a 与 b 的值.

局部变量定义
局部变量可以在一个语句块或代码块内任意地方声明. 第一种形式，不需要表达式列表，声明变量但不赋值，所以这些变量都会将nil作为值二中形式，为局部变量赋值，参见上面的赋值.

注意：局部变量显式声明于local关键字后面，形式为local 变量名. 比如语句  声明一个名为“x”的局部变量，并将全局变量“x”的值赋予这个变量. 局部变量只在其声明的语句块结尾前的地方生效.

控制结构
当表达式（视为）是true时，反复执行while声明.

反复执行语句块，直到表达式（视为）是true. 在语句块内声明局部变量可以用于表达式中.

for循环的第一种形式会生命一个局部变量，然后从对于值exp1以exp3的步长到exp2重复代码段. 注意exp3可以省略，相当于1，但是非数字值比如 和 是错误的. 循环开始前，所有的表达式都会被求值.

这种形式的for循环大致相当于

不过变量var、limit和step在其他地方都不可访问. 注意变量“name”是语句块的局部变量；如果要在循环以外用它的值，它必须被复制到一个循环外面定义的变量.

第二种形式的for循环会与迭代函数一起作用. 就像在第一种形式里，表达式列表会在开始循环之前就赋值了.

这种形式的for循环大致相当于

除了变量func、static和var在其他地方不能被获得. 注意var-list中的变量在语句块中相当于局部变量；如要在循环外使用它们，需要复制到在循环之外声明的变量.

通常expression-list是返回3个值得一个函数调用. 如果迭代器函数可以被写入（be written），那么只取决于传入的参数，这会更加有效. 否则，在Lua中编程建议返回闭包比返回表更好，因为静止的变量在每次迭代更新其成员.

当表达式1返回true时执行代码段1，否则，当表达式2返回true时执行代码段2，否则执行代码段3. 部分可以省去， 部分可以重复，也可以省去.

返回声明用来返回从函数或者代码块（chunk）（只是一个函数）. expression-list是由逗号分隔开的零个或更多个表达式.

Lua实现尾调用（tail calls. 如果表达式列表包含一个函数调用，对那个函数的调用会重新使用当前的堆栈项（stack frame）. 这可用于处理调用堆栈的函数，比如 和.

返回声明必须是语句块（block）的最后一个声明. 如果某些原因语句块的中间需要返回，那么可能需要明显的语句块.

break语句用来中止一个while、rpeat的执行，或者对于循环，跳到循环后的下一个语句.

break声明必须是语句块（block）的最后一个声明. 如果某些原因语句块的中间需要中断，那么可能需要明显的语句块.

函数调用作为语句
函数可以作为语句被调用，此时函数的副作用（例如mw.log向日志输出信息）会发生，然而函数的返回值会被忽略.

函数声明语句
Lua提供了语法糖来使得函数的定义更加自然. 以下几种定义相互等价.

-- 基本声明 function func( var-list ) 语句块 end func = function ( var-list ) 语句块 end

-- 局部函数 local function func( var-list ) 语句块 end local func; func = function ( var-list ) 语句块 end

-- 作为表中的域的函数 function table.func( var-list ) 语句块 end table.func = function ( var-list ) 语句块 end

-- 作为表的方法的函数 function table:func( var-list ) 语句块 end table.func = function ( self, var-list ) 语句块 end

注意，这里的冒号符号与函数调用的冒号符号相类似，在参数列表的开头添加了一个隐式参数，名为“self”.

错误处理
错误可以通过error和assert“抛出”，使用pcall 或者xpcall可以“捕获”错误. 注意，某些Scribunto的内部错误是不能被Lua层面的代码捕获处理.

垃圾回收
Lua能自动管理内存. 这意味着你不需要关心新建对象时内存空间的申请，或者对象不需使用时内存空间的释放. Lua的内存管理会自动执行“垃圾回收”，将不会再被访问的死对象或者被弱引用保持的对象的内存空间收回. 几乎所有Lua类型元素都能被回收，包括表、方法、字符串等.

垃圾回收是自动运行的，不能被Scribunto配置.

标准库
Lua标准库为Lua提供基本的性能和关键功能. 只有Lua标准库再Scribunto启用的一部分内容会在此说明.

_G


这个变量持有对当前全局变量表的引用；全局变量 也会被关联到. 注意，然而，对_G本身并没有什么特别的；它可能被以同样的方式作为任何其他变量：

全局变量表可以当作普通的表来使用. 例如，

_VERSION


包含正在运行的Lua语言版本的字符串，例如“Lua 5.1”.

assert
如果 是空值（nil）或是假（布尔值false），就会产生错误，那么 就会用作错误的文本：如果nil（或者未指定），文字是“assertion failes!（声明失败！）”；如果是字符串或者数字，文字就是那个值；否则声明（assert）本身就会引发错误.

如果 是任何其他的值，声明（assert）就会返回包括 和 在内的全部变量.

在Lua的一个比较常见的惯用用法是一个函数返回正常操作时的true值，并在失败时返回0或false作为为第一个值，错误信息作为第二值. 容易的错误检查可以通过调用函数 来实现：

error
用文本 来发出一个错误.

一般会提供出错的位置的信息. 如果 是1或者省略，纳闷信息就是调用 本身的位置，2使用被调用错误的函数调用的位置，等等. 0会省略位置信息.

getfenv
注意，这个函数可能会无效，取决于配置中的.

返回运行环境（全局变量），由 指定：


 * 如果1、nil或者未指定，返回调用 函数的环境. 通常这与_G相同.
 * 整数2～10返回更高一级的环境. 例如，2返回被这一个函数调用的函数的环境，3返回调用这一个函数的函数的环境，以此类推. 如果这个堆栈值越高，错误也会随之上升，否则这个堆栈级别会返回尾调用（tail call）.
 * 传递函数返回在调用该函数时将使用的环境.

通过所有的基本函数和Scribunto基本库函数使用的环境都被保护. 尝试访问这些环境中使用 将返回nil.

getmetatable
返回这个表的元表. 其他的类型都会返回nil.

如果元表拥有 欄位，这个值就会直接返回，而不是返回对应的元表.

ipairs
返回3个值：迭代函数，表 和0. 它是供 的迭代形式：

它会迭代数对(1, t[1])、(2,t[2])等，直到t[i]是nil时.

如果 metamethod存在，那么标准行为会被覆盖，调用会返回与 的返回值一致的值.

next
允许遍历表中的键. 如果 是nil或者未指定，返回表中的第一个键和值，否则，返回下一个键和值. 如果没有更多的键可以用，返回nil. 可以通过使用 来检查表是否是空的.

注意键被返回的顺序是没有指定的，即使表有数字的索引（indexes）. 如要以数字顺序遍历表，使用数字的for或ipairs.

Behavior is undefined if, when using next for traversal, any non-existing key is assigned a value. Assigning a new value (including nil) to an existing field is allowed.

pairs
返回三个值：迭代器函数（next或者类似的）、表 和nil. 这是用于 的迭代器形式.

这会遍历 中的键值对，就像next做得那样. 参考next的文档以了解遍历期间修改表的限制.

如果__pairs原方法存在，那么标准行为会被覆盖，调用会返回与 的返回值一致的值.

pcall
用指定的参数在“保护模式”下调用函数. 这意味着如果在调用 时一个错误发生，pcall会返回false与错误消息. 如果没有错误发生，pcall会返回true与调用返回的所有值.

在伪代码中， 的定义类似如下：

rawequal
与 相同，只是忽略了所有__eq元方法.

rawget
与 相同，只是忽略了所有__index元方法.

rawset
与 相同，只是忽略了所有__newindex元方法.

select
如果 是数字，返回 后对应的位置的数. 如果 是字符串"#"，返回 中参数的个数.

也就是说， 有点像以下代码，只是即使当 包含nil值时也可以正常工作（参考#和unpack以了解关于nil的问题）.

setmetatable
设置表的元表，但是必须是清楚地提供的.

如果当前的原表有一个__metatable域， 会报错.

tonumber
尝试将 转化为数字. 如果已经是数字或者可以转化为数字的字符串， 就会返回这个数字，否则会返回nil.

是可选的，默认为10，指定解析数字的进位基数. 这个基数可以是2到36之间的任何整数. 对于大于10，字母A（大小写均可）代表10，B代表11，以此类推，Z代表35.

十进制下，值可以有小数部分，或者以科学计数法表示，而且甚至可以以“0x”开头以表示16进制. 其他情况，只有纯整数是接受的.

tostring
将 转化为字符串. 参考上方的数据类型以了解各种类型被转换时的细节.

对于表，标准的转换行为可以被__tostring元方法覆盖. 如果这个元方法存在，那么调用tostring会返回由 返回的单个值.

type
以字符串形式返回 的类型 、 、 、 、 或.

unpack
从给定的表返回值，像 这样的如果被写出会直接返回. 和 如果没有给出或者是nil，取其默认值1和.

注意如果 不是一个序列且 是nil或未指定，则结果是不确定的，参考长度操作符以了解详细.

xpcall
这个很像 ，只是错误消息在返回之前传递到函数 中.

在伪代码中， 的定义类似如下：

debug.traceback
以字符串的形式返回调用栈. 可选的message参数会被连接到调用栈信息的前面. 可选的level参数表示返回多少层调用栈.

math.abs
返回 的绝对值.

math.acos
返回 的反余弦值（以弧度表示）.

math.asin
返回 的反正弦值（以弧度表示）.

math.atan
返回 的反正切值（以弧度表示）.

math.atan2
使用两个参数的符号（signs）以找到结果的象限，返回 的反正切值（弧度制）.

math.ceil
返回不小于 的最小整数.

math.cos
返回 （以弧度表示）的余弦值.

math.cosh
返回 的双曲余弦值.

math.deg
将弧度角 转化为角度.

math.exp
返回$$e^x$$.

math.floor
返回小于或等于 的最大整数.

math.fmod
返回 除以 的余数，并将商舍入到零. 比如， 产生.

math.frexp
返回像这样的两个值 和 ：


 * 如果 是无穷大且非零，那么$$x = m \times 2^e$$、 是整数， 的绝对值在$$[0.5, 1)$$区间内
 * 如果 是零，那么 和 都是0
 * 如果 是NaN（非数字）或无穷大，那么 是 而 不指定

math.huge
代表正无穷大的值；比任何其他数值都要大或与之相等.

math.ldexp
返回$$m \times 2^e$$（ 是整数）.

math.log
返回 的自然对数.

math.log10
返回 的以10为底的对数.

math.max
返回其参数的最大值.

对于NaN的行为未指定. 当前，如果 是NaN，那么会返回NaN，但是其他的NaN就会被忽略.

math.min
返回其参数的最小值.

对于NaN的行为未指定. 当前，如果 是NaN，那么会返回NaN，但是其他的NaN就会被忽略.

math.modf
返回两个数字， 的整数部分和 的小数部分. 比如， 产生.

math.pi
$$\pi$$的值.

math.pow
与 相同.

math.rad
将角度 转化为弧度角.

math.random
返回伪随机数.

参数 、 可省略，但是如果指定了，则必须能够转化为整数.


 * 没有参数时返回区间$$[0,1)$$内的实数.
 * 有一个参数时返回区间$$[1,m]$$内的整数.
 * 有两个参数时返回区间$$[m,n]$$内的整数.

math.randomseed
以 作为伪随机数生成器的种子.

注意使用同一个种子会导致 输出相同的数列.

math.sin
返回 （以弧度表示）的正弦值.

math.sinh
返回 的双曲正弦值.

math.sqrt
返回 的平方根. 与 相同.

math.tan
返回 （以弧度表示）的正切值.

math.tanh
返回 的双曲正切值.

os.clock
返回程序大约使用的CPU时间，以秒为单位.

os.date

 * 语言库的formatDate可以被用于更加全面的日期格式.

返回包含日期和时间的字符串或表，以 为格式. 如果格式被省略或者是nil，则使用“%c”.

如果给定了 ，则就是被格式化的时间（参考. 否则使用当前的时间.

如果 以!开头，则日期按照UTC格式而不是服务器的本地时间. 在这个可选字符之后，如果格式是字符串"*t"，那么日期返回带有以下域的表.


 * year（完整的）
 * month（1～12）
 * day（1～31）
 * hour（0～23）
 * min（0～59）
 * sec（0～60）
 * wday（weekday，Sunday是1）
 * yday（一年的某一天）
 * isdst（夏令时，布尔值，信息不可用时可能不存在）

如果格式不是"*t"，那么日期以字符串形式返回日期，按照和C函数strftime相同的规则格式化.

os.difftime
返回从 到 两个时间的秒数.

os.time
返回代表当前时间的数字.

调用且没有变量时，返回当前时间. 若传入了表，则表中编码的时间就会被解析. 表必须有years、month、days这几个域，并且可能也包括hour（默认为12）、min（默认为0）、sec（默认为0）和isdst.

require
加载目标模块.

首先会检查 以检查模块是否已被加载，如果是，返回.

Otherwise, it calls each loader in the  sequence to attempt to find a loader for the module. If a loader is found, that loader is called. The value returned by the loader is stored into  and is returned.

See the documentation for  for information on the loaders available.

例如，如果你有一个模块“模块:Giving”其中有如下代码：

你可以用以下代码在其它模块载入此模块：

package.loaded
This table holds the loaded modules. The keys are the module names, and the values are the values returned when the module was loaded.

package.loaders
This table holds the sequence of searcher functions to use when loading modules. Each searcher function is called with a single argument, the name of the module to load. If the module is found, the searcher must return a function that will actually load the module and return the value to be returned by require. Otherwise, it must return nil.

Scribunto提供了两种搜索方式：


 * 1) Look in   for the loader function
 * 2) Look in the modules provided with Scribunto for the module name, and if that fails look in the Module: namespace. The "Module:" prefix must be provided.

Note that the standard Lua loaders are not included.

package.preload
This table holds loader functions, used by the first searcher Scribunto includes in package.loaders.

package.seeall
Sets the __index metamethod for  to _G.

字符串（string）库
在所有字符串函数中，第一个字符是第1位，而不是像C、PHP、JavaScript中的那样第0位. 索引（indexes）可以是负的，表示从字符串最末开始倒数，比如-1表示最后一个字符，-2表示倒数第二个，等等.

字符串库假定单字节字符串编码. 不能处理Unicode字符. 要对Unicode字符进行操作，使用Scribunto Ustring库中对应的方法.

string.byte
如果字符串被考虑为字节的数组，返回 、 、···、 的字节值. 的默认值为1； 的默认值为. 等价于mw.ustring.byte.

string.char
接受零个或更多个整数. 返回和长度与参数个数相同的字符串，每个字符的字节值等于其对应的参数.

参看mw.ustring.char以了解使用Unicode codepoint而非字节值的类似函数.

string.find
寻找字符串 中第一个匹配的. 如果找到一个匹配，返回 中起止点的序列，否则返回nil. If the pattern has captures,then in a successful match the captured values are also returned after the two indices.

第三个参数 是可选的，指定从哪里开始搜索，默认值是1，可以是负数. 第四个参数 也是可选的，如果是true，则会关闭模式匹配机制，则函数做的只是简单地“找子串”操作， 中的字符就不会被看作魔法字符.

注意给了 就必须给.

参考mw.ustring.find以了解用于Ustring pattern的类似函数，而且 是按照字符而非字节.

string.format
返回变量数字的参数将第一个参数（必须是字符串）格式化后的版本.

格式字符串使用格式指定器但有所限制.


 * “-”“+”“ ”“#”和“0”是被认可的.
 * 支持最多99个整数域. “*”不支持.
 * 支持最多99个整数精确度. “*”不支持.
 * 长度修改器不支持.
 * 认可c、d、i、o、u、x、X、e、E、f、g、G、s、%这些转换器，以及非标准的q.
 * 不支持像“%2$s”这样的位置指定器.

转换指定器q类似于s，但是会以特定的专用于表述字符串的格式来形成字符串；字符串会被写在双引号中，所有的双引号、新行、嵌入的零、反斜杠都会被转义.

数字和字符串之间的转换会像数据类型中说的那严格：其他类型不会自动转化为字符串. 包含NUL字符的字符串（字节值0）不能被正常处理.

等同于mw.ustring.format.

string.gmatch
返回一个迭代器函数，每次被调用，都会从字符串 中的 返回下一个捕获. 如果 不会指定捕获，则整个匹配都会在每次调用时产生.

对于这个函数，开始的 不是魔法字符，因为这个会避免迭代. 它被看做是普通字符.

参看mw.ustring.gmath以了解其类似函数，其匹配模式是被扩展的，参考Ustring匹配模式.

string.gsub
将字符串 的所有（或者前 个）出现的 替换为由 指定的替换，这个替换可以是字符串、表或者函数，然后返回替换后的字符串. 也会返回，作为第二个值，发生匹配的总次数.

如果 是一个字符串，则其值直接用于替换. 字符 用作转义符（escape character）： 中的任何 形式的序列，n是1到9之间，代表第n个被捕获的子串. 序列 代表整个匹配（match），序列 代表单个.

如果 是表，则每次匹配查询这个表，其键（key）为第一个捕获（capture）；如果匹配模式（pattern）不指定捕获，则整个匹配（match）用作键.

如果 是函数，则每次匹配发生时调用这个函数，所有被捕获的子串都会依次被传入作为参数. 如果匹配模式不指定捕获，则整个匹配会作为单个参数传入函数.

如果表格查询或者函数调用返回的值是字符串或者数字，则用作替换字符串，否则，如果是false或nil，则不会进行替换，也就是说原始匹配仍保留在字符串中.

参看mw.ustring.gsub以了解其类似函数，其匹配模式是被扩展的，参考Ustring匹配模式.

string.len
返回字符串的字节长度. 不会被ASCII NUL字符混淆. 等同于#s.

参看mw.ustring.len以了解使用Unicode codepoint而非字节值的类似函数.

string.lower
将字符串的所有ASCII大写字符转为小写后返回. 所有其他字符不改变.

参考mw.ustring.lower以了解类似的函数，该函数可以将Unicode定义的所有的大写字母转化为小写字母.

string.match
寻找字符串中 的第一个匹配，如果找到一个，则 返回从样式匹配中的捕获，否则返回nil. 如果 不指定捕获，则返回整个字符串.

第三个参数 是可选的，用来表示从哪里开始搜索，其默认值为1，可以是负数.

参看mw.ustring.math以了解其类似函数，其匹配模式是被扩展的，参考Ustring匹配模式.

string.rep
返回字符串 重复 次并连接后的字符串. 等价于mw.ustring.rep.

string.reverse
返回字符串 被逆转后的字符串（按字节逆转）.

string.sub
返回 的从 开始持续到 的子串（substring）； 和 可以是负的. 如果 是nil或未指定，则会一直到字符串末尾.

注意字符串是从索引1开始的. 使用这个函数时，两边的所有索引都是包括的（inclusive）.

特别地，调用 会返回字符串 的长度 的前缀，而 会返回字符串 的长度为 的后缀.

参看mw.ustring.sub以了解使用字符而非字节值的类似函数.

string.upper
将字符串的所有ASCII小写字符转为大写后返回. 所有其他字符不改变.

参考$anchor以了解类似的函数，该函数可以将Unicode定义的所有的小写字母转化为大写字母.

模式匹配
注意Lua的样式匹配类似于正则表达式（regular expression），但是并不一样. 特别地，注意正则表达式和PCRE之间的以下区别.


 * 用于引用的字符串是百分号（ ）而非反斜杠（ ）.
 * 点（ ）总是匹配所有字符，包括新行.
 * 没有大小写不敏感模式.
 * 没有选择功能（ 操作符）.
 * 量词（quantifier， 、 、 和 ）不能用于单独的字符或者字符类，不能捕获组.
 * 唯一非贪婪的量词是 ，相当于PCRE的 量词.
 * 没有广义的有限量词，比如PCRE中的.
 * 零宽的assertion是 、 和 frontier样式，像PCRE的 和 不可用.
 * 样式匹配本身不认识像'\"ddd"'这样的转义. 然而，由于样式匹配是字符串，这一类转义或许可以用于在创建样式匹配字符串的文字.

注意样式匹配不能包含嵌入的零字节（ASCII NUL， ）. 应该使用.

参考Ustring样式匹配以了解使用Unicode字符的类似的样式匹配机制.

字符类
字符类是一组字符的集合. 以下集合可以用于定义字符类.


 * x: (where x is not one of the magic characters ) represents the character x itself.
 *  : (a dot) represents all characters.
 *  : represents all ASCII letters.
 *  : represents all ASCII control characters.
 *  : represents all digits.
 *  : represents all ASCII lowercase letters.
 *  : represents all punctuation characters.
 *  : represents all ASCII space characters.
 *  : represents all ASCII uppercase letters.
 *  : represents all ASCII alphanumeric characters.
 *  : represents all hexadecimal digits.
 *  : represents ASCII NUL, the zero byte.
 *  : All characters not in.
 *  : All characters not in.
 *  : All characters not in.
 *  : All characters not in.
 *  : All characters not in.
 *  : All characters not in.
 *  : All characters not in.
 *  : All characters not in.
 *  : All characters not in.
 *  : All characters not in.
 *  : (where x is any non-alphanumeric character) represents the character x. This is the standard way to escape the magic characters. Any punctuation character (even the non magic) can be preceded by a ' ' when used to represent itself in a pattern.
 *  : 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 with a ' '. All classes  described above can also be used as components in set. All other characters in set represent themselves. For example,   (or  ) represents all alphanumeric characters plus the underscore,   represents the octal digits, and   represents the octal digits plus the lowercase letters plus the ' ' character. The interaction between ranges and classes is not defined. Therefore, patterns like   or   have no meaning.
 *  : represents the complement of set, where set is interpreted as above.

Pattern items
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 0 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 1 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 0 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 0 or 1 occurrence of a character in the class;
 * , for n between 1 and 9; such item matches a substring equal to the n-th captured string (see below);
 * , 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  matches expressions with balanced parentheses.


 * , 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'. Note that frontier patterns were present but undocumented in Lua 5.1, and officially added to Lua in 5.2. The implementation in Lua 5.2.1 is unchanged from that in 5.1.0.

Pattern
A pattern is a sequence of pattern items.

A ' ' 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, the part of the string matching   is stored as the first capture (and therefore has number 1); the character matching   is captured with number 2, and the part matching   has number 3.

Capture references can appear in the pattern string itself, and refer back to text that was captured earlier in the match. For example,  will match any pair of identical lowercase letters, while   will match any 7-letter palindrome.

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

表库
这个库的大多数函数假设作为参数的表是序列

The functions,  , and   may be available but are deprecated. Use a for loop with pairs, a for loop with ipairs, and the length operator instead.

table.concat
Given an array where all elements are strings or numbers, returns.

The default value for  is the empty string, the default for   is 1, and the default for   is the length of the table. If  is greater than , returns the empty string.

table.insert
Inserts element  at position   in , shifting up other elements to open space, if necessary. The default value for  is the length of the table plus 1, so that a call   inserts   at the end of table.

Elements up to  are shifted; see Length operator for caveats if the table is not a sequence.

table.maxn
Returns the largest positive numerical index of the given table, or zero if the table has no positive numerical indices.

To do this, it iterates over the whole table. This is roughly equivalent to

table.remove
Removes from  the element at position  , shifting down other elements to close the space, if necessary. Returns the value of the removed element. The default value for  is the length of the table, so that a call   removes the last element of table.

Elements up to  are shifted; see Length operator for caveats if the table is not a sequence.

table.sort
Sorts table elements in a given order, in-place, from  to. If  is given, then it must be a function that receives two table elements, and returns true when the first is less than the second (so that   will be true after the sort). If  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.

Scribunto库
所有Scribunto库位于表 中.

mw.addWarning
Adds a warning which is displayed above the preview when previewing an edit. is parsed as wikitext.

mw.allToString
Calls tostring on all arguments, then concatenates them with tabs as separators.

mw.clone
深拷贝一个值. 所有的表和它们的元表被重构，但是新表和旧表共用函数.

mw.getCurrentFrame
返回目前的框架项目，通常是从最近的 中的框架函数.

mw.incrementExpensiveFunctionCount
使得“高代价解析器函数”计数器加一，并在其超过限制时抛出异常. 参见

mw.isSubsting
Returns true if the current  is being substed, false otherwise. See Returning text above for discussion on differences when substing versus not substing.

mw.loadData
Sometimes a module needs large tables of data; for example, a general-purpose module to convert units of measure might need a large table of recognized units and their conversion factors. And sometimes these modules will be used many times in one page. Parsing the large data table for every  can use a significant amount of time. To avoid this issue,  is provided.

works like, with the following differences:


 * The loaded module is evaluated only once per page, rather than once per  call.
 * The loaded module is not recorded in.
 * The value returned from the loaded module must be a table. Other data types are not supported.
 * The returned table (and all subtables) may contain only booleans, numbers, strings, and other tables. Other data types, particularly functions, are not allowed.
 * The returned table (and all subtables) may not have a metatable.
 * All table keys must be booleans, numbers, or strings.
 * The table actually returned by  has metamethods that provide read-only access to the table returned by the module. Since it does not contain the data directly,   and   will work but other methods, including ,  , and the functions in the Table library, will not work correctly.

The hypothetical unit-conversion module mentioned above might store its code in "Module:Convert" and its data in "Module:Convert/data", and "Module:Convert" would use  to efficiently load the data.

mw.dumpObject
将 序列化为人类可读的字符串值并返回.

mw.log
Passes the arguments to mw.allToString, then appends the resulting string to the log buffer.

In the debug console, the function  is an alias for this function.

mw.logObject
Calls mw.dumpObject and appends the resulting string to the log buffer. If  is given, it will be added to the log buffer followed by an equals sign before the serialized string is appended (i.e. the logged text will be "prefix = object-string").

Frame对象
框架（frame对象）是接口. 通过框架来访问传递至 和解析器函数的参数.

Note that there is no frame library, and there is no global variable named. A frame object is typically obtained by being passed as a parameter to the function called by, and can also be obtained from.

frame.args
用来访问传递到frame的参数的表. 例如，一个模块从如下的维基文本调用

那么 会返回 ， 会返回 ， 或 会返回. 在参数列表迭代可以使用 或 然而基于Lua对迭代器的实现，迭代的顺序不确定，参数出现在维基文本中的顺序也无从得知.

Note that values in this table are always strings;  may be used to convert them to numbers, if necessary. Keys, however, are numbers even if explicitly supplied in the invocation:  gives string values   and   indexed by numeric keys   and.

As in MediaWiki template invocations, named arguments will have leading and trailing whitespace removed from both the name and the value before they are passed to Lua, whereas unnamed arguments will not have whitespace stripped.

For performance reasons,  uses a metatable, rather than directly containing the arguments. Argument values are requested from MediaWiki on demand. This means that most other table methods will not work correctly, including,  , and the functions in the Table library.

If preprocessor syntax such as template invocations and triple-brace arguments are included within an argument to #invoke, they will not be expanded, after being passed to Lua, until their values are being requested in Lua. If certain special tags written in XML notation, such as,  ,   and  , are included as arguments to #invoke, then these tags will be converted to "strip markers" — special strings which begin with a delete character (ASCII 127), to be replaced with HTML after they are returned from #invoke.

frame:callParserFunction

 * 使用具名参数的说明.

调用解析器函数，返回一个适当的字符串. 当可能时，最好优先使用原生的Lua函数或Scribunto库函数.

以下调用与以下维基文本基本相同：

Note that, as with frame:expandTemplate, the function name and arguments are not preprocessed before being passed to the parser function.

frame:expandTemplate

 * 使用具名参数的说明.

这是嵌入包含. 函数

frame:expandTemplate{ title = 'template', args = { 'arg1', 'arg2', name = 'arg3' } }

在Lua脚本中的行为大致和 在维基文本中的行为一样. 如果页面名没有名字空间前缀，那么函数会认为页面在模板名字空间内.

注意标题与参数在传递到模版之前并未预处理：

frame:extensionTag
This is equivalent to a call to frame:callParserFunction with function name  and with   prepended to.

frame:getParent
Called on the frame created by, returns the frame for the page that called. Called on that frame, returns nil.

For instance, if the template  contains the code , and a page transcludes that template and supplies arguments to it , calling   in Module:ModuleName will return.

frame:getTitle
Returns the title associated with the frame as a string. For the frame created by, this is the title of the module invoked.

frame:newChild

 * 使用具名参数的说明.

Create a new Frame object that is a child of the current frame, with optional arguments and title.

This is mainly intended for use in the debug console for testing functions that would normally be called by. The number of frames that may be created at any one time is limited.

frame:preprocess
This expands wikitext in the context of the frame, i.e. templates, parser functions, and parameters such as  are expanded. Certain special tags written in XML-style notation, such as,  ,   and  , will be replaced with "strip markers" &mdash; special strings which begin with a delete character (ASCII 127), to be replaced with HTML after they are returned from.

If you are expanding a single template, use  instead of trying to construct a wikitext string to pass to this method. It's faster and less prone to error if the arguments contain pipe characters or other wikimarkup.

If you are expanding a single parser function, use  for the same reasons.

frame:getArgument
Gets an object for the specified argument, or nil if the argument is not provided.

The returned object has one method,, that returns the expanded wikitext for the argument.

frame:newParserValue
Returns an object with one method,, that returns the result of.

frame:newTemplateParserValue

 * 使用具名参数的说明.

Returns an object with one method,, that returns the result of   called with the given arguments.

frame:argumentPairs
Same as. Included for backwards compatibility.

mw.hash.hashValue
Hashes a string value with the specified algorithm. Valid algorithms may be fetched using mw.hash.listAlgorithms.

mw.hash.listAlgorithms
Returns a list of supported hashing algorithms, for use in mw.hash.hashValue.

HTML库
是用于在Lua中构建复杂HTML树的友好接口. 使用 方法来创建mw.html对象.

Functions documented as  are available on the global   table; functions documented as   and   are methods of an mw.html object (see  ).

一个基础的例子如下所示：

mw.html.create
Creates a new mw.html object containing a  html element. You can also pass an empty string or nil as  in order to create an empty mw.html object.

can be a table with the following keys:


 * : Force the current tag to be self-closing, even if mw.html doesn't recognize it as self-closing
 * : Parent of the current mw.html instance (intended for internal usage)

mw.html:node
向当前的mw.html实例附加mw.html子元素. 如果传递nil，那么函数不做任何事. 参数代表要创建的HTML元素的种类.

mw.html:wikitext
Appends an undetermined number of wikitext strings to the mw.html object.

Note that this stops at the first nil item.

mw.html:newline
Appends a newline to the mw.html object.

mw.html:tag
Appends a new child node with the given  to the builder, and returns a mw.html instance representing that new node. The  parameter is identical to that of

mw.html:attr
Set an HTML attribute with the given  and   on the node. Alternatively a table holding name->value pairs of attributes to set can be passed. In the first form, a value of nil causes any attribute with the given name to be unset if it was previously set.

mw.html:getAttr
Get the value of a html attribute previously set using  with the given.

mw.html:addClass
Adds a class name to the node's class attribute. If a nil parameter is passed, this is a no-op.

mw.html:css
Set a CSS property with the given  and   on the node. Alternatively a table holding name->value pairs of properties to set can be passed. In the first form, a value of nil causes any property with the given name to be unset if it was previously set.

mw.html:cssText
Add some raw  to the node's style attribute. If a nil parameter is passed, this is a no-op.

mw.html:done
Returns the parent node under which the current node was created. Like jQuery.end, this is a convenience function to allow the construction of several child nodes to be chained together into a single statement.

mw.html:allDone
Like, but traverses all the way to the root node of the tree and returns it.

语言库
Language codes are described at language code. Many of MediaWiki's language codes are similar to IETF language tags, but not all MediaWiki language codes are valid IETF tags or vice versa.

Functions documented as  are available on the global   table; functions documented as   and   are methods of a language object (see   or  ).

mw.language.fetchLanguageName
The full name of the language for the given language code: native name (language autonym) by default, name translated in target language if a value is given for.

mw.language.fetchLanguageNames
Fetch the list of languages known to MediaWiki, returning a table mapping language code to language name.

By default the name returned is the language autonym; passing a language code for  returns all names in that language.

By default, only language names known to MediaWiki are returned; passing  for   will return all available languages (e.g. from Extension:CLDR), while passing   will include only languages having customized messages included with MediaWiki core or enabled extensions. To explicitly select the default,  may be passed.

mw.language.getContentLanguage
Returns a new language object for the wiki's default content language.

mw.language.getFallbacksFor


Returns a list of MediaWiki's fallback language codes for the specified code.

mw.language.isKnownLanguageTag
Returns true if a language code is known to MediaWiki.

A language code is "known" if it is a "valid built-in code" (i.e. it returns true for ) and returns a non-empty string for.

mw.language.isSupportedLanguage
Checks whether any localisation is available for that language code in MediaWiki.

A language code is "supported" if it is a "valid" code (returns true for ), contains no uppercase letters, and has a message file in the currently-running version of MediaWiki.

It is possible for a language code to be "supported" but not "known" (i.e. returning true for ). Also note that certain codes are "supported" despite  returning false.

mw.language.isValidBuiltInCode
Returns true if a language code is of a valid form for the purposes of internal customisation of MediaWiki.

The code may not actually correspond to any known language.

A language code is a "valid built-in code" if it is a "valid" code (i.e. it returns true for ); consists of only ASCII letters, numbers, and hyphens; and is at least two characters long.

Note that some codes are "supported" (i.e. returning true from ) even though this function returns false.

mw.language.isValidCode
Returns true if a language code string is of a valid form, whether or not it exists. This includes codes which are used solely for customisation via the MediaWiki namespace.

The code may not actually correspond to any known language.

A language code is valid if it does not contain certain unsafe characters (colons, single- or double-quotes, slashs, backslashs, angle brackets, ampersands, or ASCII NULs) and is otherwise allowed in a page title.

mw.language.new
Creates a new language object. Language objects do not have any publicly accessible properties, but they do have several methods, which are documented below.

There is a limit on the number of distinct language codes that may be used on a page. Exceeding this limit will result in errors.

mw.language:getCode
Returns the language code for this language object.

mw.language:getFallbackLanguages
Returns a list of MediaWiki's fallback language codes for this language object. Equivalent to.

mw.language:isRTL
Returns true if the language is written right-to-left, false if it is written left-to-right.

mw.language:lc
Converts the string to lowercase, honoring any special rules for the given language.

When the Ustring library is loaded, the mw.ustring.lower function is implemented as a call to.

mw.language:lcfirst
Converts the first character of the string to lowercase, as with lang:lc.

mw.language:uc
Converts the string to uppercase, honoring any special rules for the given language.

When the Ustring library is loaded, the mw.ustring.upper function is implemented as a call to.

mw.language:ucfirst
Converts the first character of the string to uppercase, as with lang:uc.

mw.language:caseFold
Converts the string to a representation appropriate for case-insensitive comparison. Note that the result may not make any sense when displayed.

mw.language:formatNum
Formats a number with grouping and decimal separators appropriate for the given language. Given 123456.78, this may produce "123,456.78", "123.456,78", or even something like "١٢٣٬٤٥٦٫٧٨" depending on the language and wiki configuration.

The  is a table of options, which can be:


 * : Set true to omit grouping separators and use a dot as the decimal separator. Digit transformation may still occur, which may include transforming the decimal separator.

mw.language:formatDate
Formats a date according to the given format string. If  is omitted, the default is the current time. The value for  must be a boolean or nil; if true, the time is formatted in the wiki's local time rather than in UTC.

The format string and supported values for  are identical to those for the #time parser function from Extension:ParserFunctions. Note however that backslashes may need to be doubled in a Lua string literal, since Lua also uses backslash as an escape character while wikitext does not:

mw.language:formatDuration
Breaks a duration in seconds into more human-readable units, e.g. 12345 to 3 hours, 25 minutes and 45 seconds, returning the result as a string.

, if given, is a table with values naming the interval units to use in the response. These include 'millennia', 'centuries', 'decades', 'years', 'weeks', 'days', 'hours', 'minutes', and 'seconds'.

mw.language:parseFormattedNumber
This takes a number as formatted by lang:formatNum and returns the actual number. In other words, this is basically a language-aware version of.

mw.language:convertPlural
This chooses the appropriate grammatical form from  (which must be a sequence table) or   based on the number. For example, in English you might use  or   to generate grammatically-correct text whether there is only 1 sock or 200 socks.

The necessary values for the sequence are language-dependent, see localization of magic words and translatewiki's FAQ on PLURAL for some details.

mw.language:convertGrammar

 * Note the different parameter order between the two aliases.  matches the order of the method of the same name on MediaWiki's Language object, while   matches the order of the parser function of the same name, documented at Special:MyLanguage/Help:Magic words.

This chooses the appropriate inflected form of  for the given inflection code.

The possible values for  and   are language-dependent, see Special:MyLanguage/Help:Magic words and translatewiki:Grammar for some details.

mw.language:gender
Chooses the string corresponding to the gender of, which may be "male", "female", or a registered user name.

mw.language:getArrow
Returns a Unicode arrow character corresponding to :


 * forwards: Either "→" or "←" depending on the directionality of the language.
 * backwards: Either "←" or "→" depending on the directionality of the language.
 * left: "←"
 * right: "→"
 * up: "↑"
 * down: "↓"

mw.language:getDir
根据语言的书写方向，返回"ltr"（从左至右）或"rtl"（从右至左）.

mw.language:getDirMark
Returns a string containing either U+200E (the left-to-right mark) or U+200F (the right-to-left mark), depending on the directionality of the language and whether  is a true or false value.

mw.language:getDirMarkEntity
Returns "&amp;lrm;" or "&amp;rlm;", depending on the directionality of the language and whether  is a true or false value.

mw.language:getDurationIntervals
Breaks a duration in seconds into more human-readable units, e.g. 12345 to 3 hours, 25 minutes and 45 seconds, returning the result as a table mapping unit names to numbers.

For example,

, if given, is a table with values naming the interval units to use in the response. These include 'millennia', 'centuries', 'decades', 'years', 'days', 'hours', 'minutes', and 'seconds'.

The unit names in  may be specified in any order (currently in English only, indendantly of the language object used, and with their plural unabbreviated form only like in the returned table, where unit names are symbolic but still not translated and not grammatically changed according to their assigned value). If the input table contains only unsupported unit names, the returned table will be empty. If the input table is not specified, is nil, or is empty, a static table for any supported units (including 'seconds' for the shortest unit) will be used by default.

The specified duration in seconds is first rounded down to an integer number of the shortest desired unit. The number of members in the returned array is variable, and only unit names mapped to a non-zero value are kept in the returned table if the rounded number of seconds is strictly positive. Otherwise only the member for the shortest desired unit name ('seconds' by default) will be set to the rounded down duration.

系统消息库
This library is an interface to the localisation messages and the MediaWiki: namespace.

Functions documented as  are available on the global   table; functions documented as   and   are methods of a message object (see  ).

mw.message.new
Creates a new message object for the given message. The remaining parameters are passed to the new object's  method.

The message object has no properties, but has several methods documented below.

mw.message.newFallbackSequence
Creates a new message object for the given messages (the first one that exists will be used).

The message object has no properties, but has several methods documented below.

mw.message.newRawMessage
Creates a new message object, using the given text directly rather than looking up an internationalized message. The remaining parameters are passed to the new object's  method.

The message object has no properties, but has several methods documented below.

mw.message.rawParam
Wraps the value so that it will not be parsed as wikitext by.

mw.message.numParam
Wraps the value so that it will automatically be formatted as by. Note this does not depend on the Language library actually being available.

mw.message.getDefaultLanguage
Returns a Language object for the default language.

mw.message:params
Add parameters to the message, which may be passed as individual arguments or as a sequence table. Parameters must be numbers, strings, or the special values returned by mw.message.numParam or mw.message.rawParam. If a sequence table is used, parameters must be directly present in the table; references using the __index metamethod will not work.

Returns the  object, to allow for call chaining.

mw.message:rawParams
Like params, but has the effect of passing all the parameters through mw.message.rawParam first.

Returns the  object, to allow for call chaining.

mw.message:numParams
Like params, but has the effect of passing all the parameters through mw.message.numParam first.

Returns the  object, to allow for call chaining.

mw.message:inLanguage
Specifies the language to use when processing the message. may be a string or a table with a  method (i.e. a Language object).

The default language is the one returned by.

Returns the  object, to allow for call chaining.

mw.message:useDatabase
Specifies whether to look up messages in the MediaWiki: namespace (i.e. look in the database), or just use the default messages distributed with MediaWiki.

The default is true.

Returns the  object, to allow for call chaining.

mw.message:plain
Substitutes the parameters and returns the message wikitext as-is. Template calls and parser functions are intact.

mw.message:exists
Returns a boolean indicating whether the message key exists.

mw.message:isBlank
Returns a boolean indicating whether the message key has content. Returns true if the message key does not exist or the message is the empty string.

mw.message:isDisabled
Returns a boolean indicating whether the message key is disabled. Returns true if the message key does not exist or if the message is the empty string or the string "-".

mw.site.currentVersion
包含当前MediaWiki版本信息的字符串值.

mw.site.scriptPath
的值.

mw.site.server
The value of.

mw.site.siteName
The value of.

mw.site.stylePath
The value of.

mw.site.namespaces
Table holding data for all namespaces, indexed by number.

The data available is:


 * id: Namespace number.
 * name: Local namespace name.
 * canonicalName: Canonical namespace name.
 * displayName: Set on namespace 0, the name to be used for display (since the name is often the empty string).
 * hasSubpages: Whether subpages are enabled for the namespace.
 * hasGenderDistinction: Whether the namespace has different aliases for different genders.
 * isCapitalized: Whether the first letter of pages in the namespace is capitalized.
 * isContent: Whether this is a content namespace.
 * isIncludable: Whether pages in the namespace can be transcluded.
 * isMovable: Whether pages in the namespace can be moved.
 * isSubject: Whether this is a subject namespace.
 * isTalk: Whether this is a talk namespace.
 * defaultContentModel: The default content model for the namespace, as a string.
 * aliases: List of aliases for the namespace.
 * subject: Reference to the corresponding subject namespace's data.
 * talk: Reference to the corresponding talk namespace's data.
 * associated: Reference to the associated namespace's data.

A metatable is also set that allows for looking up namespaces by name (localized or canonical). For example, both  and   will return information about the Project namespace.

mw.site.contentNamespaces
Table holding just the content namespaces, indexed by number. See mw.site.namespaces for details.

mw.site.subjectNamespaces
Table holding just the subject namespaces, indexed by number. See mw.site.namespaces for details.

mw.site.talkNamespaces
Table holding just the talk namespaces, indexed by number. See mw.site.namespaces for details.

mw.site.stats
Table holding site statistics. Available statistics are:


 * pages: Number of pages in the wiki.
 * articles: Number of articles in the wiki.
 * files: Number of files in the wiki.
 * edits: Number of edits in the wiki.
 * users: Number of users in the wiki.
 * activeUsers: Number of active users in the wiki.
 * admins: Number of users in group 'sysop' in the wiki.

mw.site.stats.pagesInCategory


Gets statistics about the category. If  is unspecified, nil, or "*", returns a table with the following properties:


 * all: Total pages, files, and subcategories.
 * subcats: Number of subcategories.
 * files: Number of files.
 * pages: Number of pages.

If  is one of the above keys, just the corresponding value is returned instead.

Each new category queried will increment the expensive function count.

mw.site.stats.pagesInNamespace
Returns the number of pages in the given namespace (specify by number).

mw.site.stats.usersInGroup
Returns the number of users in the given group.

mw.site.interwikiMap
Returns a table holding data about available interwiki prefixes. If  is the string "local", then only data for local interwiki prefixes is returned. If  is the string "!local", then only data for non-local prefixes is returned. If no filter is specified, data for all prefixes is returned. A "local" prefix in this context is one that is for the same project. For example, on the English Wikipedia, other-language Wikipedias are considered local, while Wiktionary and such are not.

Keys in the table returned by this function are interwiki prefixes, and the values are subtables with the following properties:


 * prefix - the interwiki prefix.
 * url - the URL that the interwiki points to. The page name is represented by the parameter $1.
 * isProtocolRelative - a boolean showing whether the URL is protocol-relative.
 * isLocal - whether the URL is for a site in the current project.
 * isCurrentWiki - whether the URL is for the current wiki.
 * isTranscludable - whether pages using this interwiki prefix are transcludable. This requires scary transclusion, which is disabled on Wikimedia wikis.
 * isExtraLanguageLink - whether the interwiki is listed in.
 * displayText - for links listed in $wgExtraInterlanguageLinkPrefixes, this is the display text shown for the interlanguage link. Nil if not specified.
 * tooltip - for links listed in $wgExtraInterlanguageLinkPrefixes, this is the tooltip text shown when users hover over the interlanguage link. Nil if not specified.

文本库
The text library provides some common text processing functions missing from the String library and the Ustring library. These functions are safe for use with UTF-8 strings.

mw.text.decode
Replaces HTML entities in the string with the corresponding characters.

If boolean  is omitted or false, the only named entities recognized are '&amp;lt;', '&amp;gt;', '&amp;amp;', '&amp;quot;', and '&amp;nbsp;'. Otherwise, the list of HTML5 named entities to recognize is loaded from PHP's function.

mw.text.encode
Replaces characters in a string with HTML entities. Characters '<', '>', '&', '"', and the non-breaking space are replaced with the appropriate named entities; all others are replaced with numeric entities.

If  is supplied, it should be a string as appropriate to go inside brackets in a Ustring pattern, i.e. the "set" in. The default charset is  (the space at the end is the non-breaking space, U+00A0).

mw.text.jsonDecode
Decodes a JSON string. is 0 or a combination (use ) of the flags   and.

Normally JSON's zero-based arrays are renumbered to Lua one-based sequence tables; to prevent this, pass.

To relax certain requirements in JSON, such as no terminal comma in arrays or objects, pass. This is not recommended.

Limitations:


 * Decoded JSON arrays may not be Lua sequences if the array contains null values.
 * JSON objects will drop keys having null values.
 * It is not possible to directly tell whether the input was a JSON array or a JSON object with sequential integer keys.
 * A JSON object having sequential integer keys beginning with 1 will decode to the same table structure as a JSON array with the same values, despite these not being at all equivalent, unless  is used.

mw.text.jsonEncode
Encode a JSON string. Errors are raised if the passed value cannot be encoded in JSON. is 0 or a combination (use ) of the flags   and.

Normally Lua one-based sequence tables are encoded as JSON zero-based arrays; when  is set in , zero-based sequence tables are encoded as JSON arrays.

Limitations:


 * Empty tables are always encoded as empty arrays, not empty objects.
 * Sequence tables cannot be encoded as JSON objects without adding a "dummy" element.
 * To produce objects or arrays with nil values, a tricky implementation of the  metamethod is required.
 * A Lua table having sequential integer keys beginning with 0 will encode as a JSON array, the same as a Lua table having integer keys beginning with 1, unless  is used.
 * When both a number and the string representation of that number are used as keys in the same table, behavior is unspecified.

mw.text.killMarkers
Removes all MediaWiki strip markers from a string.

mw.text.listToText
Joins a list, prose-style. In other words, it's like  but with a different separator before the final item.

The default separator is taken from MediaWiki:comma-separator in the wiki's content language, and the default conjunction is MediaWiki:and concatenated with MediaWiki:word-separator.

Examples, using the default values for the messages:

mw.text.nowiki
Replaces various characters in the string with HTML entities to prevent their interpretation as wikitext. This includes:


 * The following characters: '"', '&', "'", '<', '=', '>', '[', ']', '{', '|', '}'
 * The following characters at the start of the string or immediately after a newline: '#', '*', ':', ';', space, tab ('\t')
 * Blank lines will have one of the associated newline or carriage return characters escaped
 * "" at the start of the string or immediately after a newline will have the first '-' escaped
 * "__" will have one underscore escaped
 * "://" will have the colon escaped
 * A whitespace character following "ISBN", "RFC", or "PMID" will be escaped

mw.text.split
Splits the string into substrings at boundaries matching the Ustring pattern. If  is specified and true,   will be interpreted as a literal string rather than as a Lua pattern (just as with the parameter of the same name for  ). Returns a table containing the substrings.

For example,  would return a table.

If  matches the empty string,   will be split into individual characters.

mw.text.gsplit
Returns an iterator function that will iterate over the substrings that would be returned by the equivalent call to.

mw.text.tag

 * 使用具名参数的说明.

Generates an HTML-style tag for.

If  is given, it must be a table with string keys. String and number values are used as the value of the attribute; boolean true results in the key being output as an HTML5 valueless parameter; boolean false skips the key entirely; and anything else is an error.

If  is not given (or is nil), only the opening tag is returned. If  is boolean false, a self-closed tag is returned. Otherwise it must be a string or number, in which case that content is enclosed in the constructed opening and closing tag. Note the content is not automatically HTML-encoded; use mw.text.encode if needed.

For properly returning extension tags such as, use frame:extensionTag instead.

mw.text.trim
Remove whitespace or other characters from the beginning and end of a string.

If  is supplied, it should be a string as appropriate to go inside brackets in a Ustring pattern, i.e. the "set" in. The default charset is ASCII whitespace,.

mw.text.truncate
Truncates  to the specified length, adding   if truncation was performed. If length is positive, the end of the string will be truncated; if negative, the beginning will be removed. If  is given and true, the resulting string including ellipsis will not be longer than the specified length.

The default value for  is taken from MediaWiki:ellipsis in the wiki's content language.

Examples, using the default "..." ellipsis:

mw.text.unstripNoWiki
Replaces MediaWiki &lt;nowiki&gt; strip markers with the corresponding text. Other types of strip markers are not changed.

mw.text.unstrip
Equivalent to.

This no longer reveals the HTML behind special page transclusion, &lt;ref&gt; tags, and so on as it did in earlier versions of Scribunto.

mw.title.equals
Test for whether two titles are equal. Note that fragments are ignored in the comparison.

mw.title.compare
Returns -1, 0, or 1 to indicate whether the title  is less than, equal to, or greater than title.

This compares titles by interwiki prefix (if any) as strings, then by namespace number, then by the unprefixed title text as a string. These string comparisons use Lua's standard  operator.

mw.title.getCurrentTitle
Returns the title object for the current page.

mw.title.new


Creates a new title object.

If a number  is given, an object is created for the title with that page_id. The title referenced will be counted as linked from the current page. If the page_id does not exist, returns nil. The expensive function count will be incremented if the title object created is not for a title that has already been loaded.

If a string  is given instead, an object is created for that title (even if the page does not exist). If the text string does not specify a namespace,  (which may be any key found in  ) will be used. If the text is not a valid title, nil is returned.

mw.title.makeTitle
Creates a title object with title  in namespace , optionally with the specified   and   prefix. may be any key found in. If the resulting title is not valid, returns nil.

Note that, unlike, this method will always apply the specified namespace. For example,  will create an object for the page Template:Module:Foo, while   will create an object for the page Module:Foo.

页面标题对象
A title object has a number of properties and methods. Most of the properties are read-only.

Note that fields ending with  return titles as string values whereas the fields ending with   return title objects.


 * id: The page_id. 0 if the page does not exist..
 * interwiki: The interwiki prefix, or the empty string if none.
 * namespace: The namespace number.
 * fragment: The fragment, or the empty string. May be assigned.
 * nsText: The text of the namespace for the page.
 * subjectNsText: The text of the subject namespace for the page.
 * text: The title of the page, without the namespace or interwiki prefixes.
 * prefixedText: The title of the page, with the namespace and interwiki prefixes.
 * fullText: The title of the page, with the namespace and interwiki prefixes and the fragment. Interwiki is not returned if equal to the current.
 * rootText: If this is a subpage, the title of the root page without prefixes. Otherwise, the same as.
 * baseText: If this is a subpage, the title of the page it is a subpage of without prefixes. Otherwise, the same as.
 * subpageText: If this is a subpage, just the subpage name. Otherwise, the same as.
 * canTalk: Whether the page for this title could have a talk page.
 * exists: Whether the page exists. Alias for file.exists for Media-namespace titles. For File-namespace titles this checks the existence of the file description page, not the file itself..
 * file, fileExists: See below.
 * isContentPage: Whether this title is in a content namespace.
 * isExternal: Whether this title has an interwiki prefix.
 * isLocal: Whether this title is in this project. For example, on the English Wikipedia, any other Wikipedia is considered "local" while Wiktionary and such are not.
 * isRedirect: Whether this is the title for a page that is a redirect..
 * isSpecialPage: Whether this is the title for a possible special page (i.e. a page in the Special: namespace).
 * isSubpage: Whether this title is a subpage of some other title.
 * isTalkPage: Whether this is a title for a talk page.
 * isSubpageOf( title2 ): Whether this title is a subpage of the given title.
 * inNamespace( ns ): Whether this title is in the given namespace. Namespaces may be specified by anything that is a key found in.
 * inNamespaces( ... ): Whether this title is in any of the given namespaces. Namespaces may be specified by anything that is a key found in.
 * hasSubjectNamespace( ns ): Whether this title's subject namespace is in the given namespace. Namespaces may be specified by anything that is a key found in.
 * contentModel: The content model for this title, as a string..
 * basePageTitle: The same as.
 * rootPageTitle: The same as.
 * talkPageTitle: The same as, or nil if this title cannot have a talk page.
 * subjectPageTitle: The same as.
 * redirectTarget: Returns a title object of the target of the redirect page if the page is a redirect and the page exists, returns false otherwise.
 * protectionLevels: The page's protection levels. This is a table with keys corresponding to each action (e.g., "edit" and "move"). The table values are arrays, the first item of which is a string containing the protection level. If the page is unprotected, either the table values or the array items will be nil..
 * cascadingProtection: The cascading protections applicable to the page. This is a table with keys "restrictions" (itself a table with keys like protectionLevels has) and "sources" (an array listing titles where the protections cascade from). If no protections cascade to the page, "restrictions" and "sources" will be empty..
 * subPageTitle( text ): The same as.
 * partialUrl: Returns  encoded as it would be in a URL.
 * fullUrl( query, proto ): Returns the full URL (with optional query table/string) for this title.  may be specified to control the scheme of the resulting url: "http", "https", "relative" (the default), or "canonical".
 * localUrl( query ): Returns the local URL (with optional query table/string) for this title.
 * canonicalUrl( query ): Returns the canonical URL (with optional query table/string) for this title.
 * getContent: Returns the (unparsed) content of the page, or nil if there is no page. The page will be recorded as a transclusion.

Title objects may be compared using relational operators. will return.

Since people find the fact surprising, note that accessing any expensive field on a title object records a "link" to the page (as shown on Special:WhatLinksHere, for example). Using the title object's  method or accessing the   field records it as a "", and accessing the title object's   or   fields records it as a "".

文件元数据
Title objects representing a page in the File or Media namespace will have a property called. This is a table, structured as follows:


 * exists: Whether the file exists. It will be recorded as an image usage. The  property on a Title object exists for backwards compatibility reasons and is an alias for this property. If this is false, all other file properties will be nil.
 * width: The width of the file. If the file contains multiple pages, this is the width of the first page.
 * height: The height of the file. If the file contains multiple pages, this is the height of the first page.
 * pages: If the file format supports multiple pages, this is a table containing tables for each page of the file; otherwise, it is nil. The # operator can be used to get the number of pages in the file. Each individual page table contains a width and height property.
 * size: The size of the file in bytes.
 * mimeType: The MIME type of the file.

Expensive properties
The properties id, isRedirect, exists, and contentModel require fetching data about the title from the database. For this reason, the expensive function count is incremented the first time one of them is accessed for a page other than the current page. Subsequent accesses of any of these properties for that page will not increment the expensive function count again.

Other properties marked as expensive will always increment the expensive function count the first time they are accessed for a page other than the current page.

mw.uri.encode
Percent-encodes the string. The default type,, encodes spaces using '+' for use in query strings;   encodes spaces as %20; and   encodes spaces as '_'.

Note that the "WIKI" format is not entirely reversible, as both spaces and underscores are encoded as '_'.

mw.uri.decode
Percent-decodes the string. The default type,, decodes '+' to space;   does not perform any extra decoding; and   decodes '_' to space.

mw.uri.anchorEncode
Encodes a string for use in a MediaWiki URI fragment.

mw.uri.buildQueryString
Encodes a table as a URI query string. Keys should be strings; values may be strings or numbers, sequence tables, or boolean false.

mw.uri.parseQueryString
Decodes the query string  to a table. Keys in the string without values will have a value of false; keys repeated multiple times will have sequence tables as values; and others will have strings as values.

The optional numerical arguments  and   can be used to specify a substring of   to be parsed, rather than the entire string. is the position of the first character of the substring, and defaults to 1. is the position of the last character of the substring, and defaults to the length of the string. Both  and   can be negative, as in string.sub.

mw.uri.canonicalUrl
Returns a URI object for the canonical URL for a page, with optional query string/table.

mw.uri.fullUrl
Returns a URI object for the full URL for a page, with optional query string/table.

mw.uri.localUrl
Returns a URI object for the local URL for a page, with optional query string/table.

mw.uri.new
Constructs a new URI object for the passed string or table. See the description of URI objects for the possible fields for the table.

mw.uri.validate
Validates the passed table (or URI object). Returns a boolean indicating whether the table was valid, and on failure a string explaining what problems were found.

URI object
The URI object has the following fields, some or all of which may be nil:


 * protocol: String protocol/scheme
 * user: String user
 * password: String password
 * host: String host name
 * port: Integer port
 * path: String path
 * query: A table, as from mw.uri.parseQueryString
 * fragment: String fragment.

The following properties are also available:
 * userInfo: String user and password
 * hostPort: String host and port
 * authority: String user, password, host, and port
 * queryString: String version of the query table
 * relativePath: String path, query string, and fragment

will give the URI string.

Methods of the URI object are:

mw.uri:parse
Parses a string into the current URI object. Any fields specified in the string will be replaced in the current object; fields not specified will keep their old values.

mw.uri:clone
Makes a copy of the URI object.

mw.uri:extend
Merges the parameters table into the object's query table.

Ustring library
The ustring library is intended to be a direct reimplementation of the standard String library, except that the methods operate on characters in UTF-8 encoded strings rather than bytes.

Most functions will raise an error if the string is not valid UTF-8; exceptions are noted.

mw.ustring.maxPatternLength
The maximum allowed length of a pattern, in bytes.

mw.ustring.maxStringLength
The maximum allowed length of a string, in bytes.

mw.ustring.byte
Returns individual bytes; identical to string.byte.

mw.ustring.byteoffset
Returns the byte offset of a character in the string. The default for both  and   is 1. may be negative, in which case it counts from the end of the string.

The character at  == 1 is the first character starting at or after byte  ; the character at   == 0 is the first character starting at or before byte. Note this may be the same character. Greater or lesser values of  are calculated relative to these.

mw.ustring.char
Much like string.char, except that the integers are Unicode codepoints rather than byte values.

mw.ustring.codepoint
Much like string.byte, except that the return values are codepoints and the offsets are characters rather than bytes.

mw.ustring.find
Much like string.find, except that the pattern is extended as described in Ustring patterns and the  offset is in characters rather than bytes.

mw.ustring.format
Identical to string.format. Widths and precisions for strings are expressed in bytes, not codepoints.

mw.ustring.gcodepoint
Returns three values for iterating over the codepoints in the string. defaults to 1, and  to -1. This is intended for use in the iterator form of :

mw.ustring.gmatch
Much like string.gmatch, except that the pattern is extended as described in Ustring patterns.

mw.ustring.gsub
Much like string.gsub, except that the pattern is extended as described in Ustring patterns.

mw.ustring.isutf8
Returns true if the string is valid UTF-8, false if not.

mw.ustring.len
Returns the length of the string in codepoints, or nil if the string is not valid UTF-8.

See string.len for a similar function that uses byte length rather than codepoints.

mw.ustring.lower
Much like string.lower, except that all characters with lowercase to uppercase definitions in Unicode are converted.

If the Language library is also loaded, this will instead call lc on the default language object.

mw.ustring.match
Much like string.match, except that the pattern is extended as described in Ustring patterns and the  offset is in characters rather than bytes.

mw.ustring.rep
Identical to string.rep.

mw.ustring.sub
Much like string.sub, except that the offsets are characters rather than bytes.

mw.ustring.toNFC
Converts the string to Normalization Form C. Returns nil if the string is not valid UTF-8.

mw.ustring.toNFD
Converts the string to Normalization Form D. Returns nil if the string is not valid UTF-8.

mw.ustring.upper
Much like string.upper, except that all characters with uppercase to lowercase definitions in Unicode are converted.

If the Language library is also loaded, this will instead call uc on the default language object.

Ustring patterns
Patterns in the ustring functions use the same syntax as the String library patterns. The major difference is that the character classes are redefined in terms of Unicode character properties:


 *  : represents all characters with General Category "Letter".
 *  : represents all characters with General Category "Control".
 *  : represents all characters with General Category "Number, decimal digit".
 *  : represents all characters with General Category "Lowercase Letter".
 *  : represents all characters with General Category "Punctuation".
 *  : represents all characters with General Category "Separator", plus tab, linefeed, carriage return, vertical tab, and form feed.
 *  : represents all characters with General Category "Uppercase Letter".
 *  : represents all characters with General Category "Letter" or "Decimal Number".
 *  : adds fullwidth character versions of the hex digits.

Like in String library patterns,  ,  ,  ,  ,  ,  ,    here represent the complementary set ("all characters without given General Category").

In all cases, characters are interpreted as Unicode characters instead of bytes, so ranges such as, patterns such as  , and quantifiers applied to multibyte characters will work correctly. Empty captures will capture the position in code points rather than bytes.

Loadable libraries
These libraries are not included by default, but if needed may be loaded using.

bit32
This emulation of the Lua 5.2  library may be loaded using

bit32 = require( 'bit32' )

The bit32 library provides bitwise operations on unsigned 32-bit integers. Input numbers are truncated to integers (in an unspecified manner) and reduced modulo 232 so the value is in the range 0 to 232−1; return values are also in this range.

When bits are numbered (as in bit32.extract), 0 is the least-significant bit (the one with value 20) and 31 is the most-significant (the one with value 231).

bit32.band
Returns the bitwise AND of its arguments: the result has a bit set only if that bit is set in all of the arguments.

If given zero arguments, the result has all bits set.

bit32.bnot
Returns the bitwise complement of.

bit32.bor
Returns the bitwise OR of its arguments: the result has a bit set if that bit is set in any of the arguments.

If given zero arguments, the result has all bits clear.

bit32.btest
Equivalent to

bit32.bxor
Returns the bitwise XOR of its arguments: the result has a bit set if that bit is set in an odd number of the arguments.

If given zero arguments, the result has all bits clear.

bit32.extract
Extracts  bits from , starting with bit. Accessing bits outside of the range 0 to 31 is an error.

If not specified, the default for  is 1.

bit32.replace
Replaces  bits in , starting with bit  , with the low   bits from. Accessing bits outside of the range 0 to 31 is an error.

If not specified, the default for  is 1.

bit32.lshift
Returns the number  shifted   bits to the left. This is a logical shift: inserted bits are 0. This is generally equivalent to multiplying by 2undefined.

Note that a displacement over 31 will result in 0.

bit32.rshift
Returns the number  shifted   bits to the right. This is a logical shift: inserted bits are 0. This is generally equivalent to dividing by 2undefined.

Note that a displacement over 31 will result in 0.

bit32.arshift
Returns the number  shifted   bits to the right. This is an arithmetic shift: if  is positive, the inserted bits will be the same as bit 31 in the original number.

Note that a displacement over 31 will result in 0 or 4294967295.

bit32.lrotate
Returns the number  rotated   bits to the left.

Note that rotations are equivalent modulo 32: a rotation of 32 is the same as a rotation of 0, 33 is the same as 1, and so on.

bit32.rrotate
Returns the number  rotated   bits to the right.

Note that rotations are equivalent modulo 32: a rotation of 32 is the same as a rotation of 0, 33 is the same as 1, and so on.

libraryUtil
This library contains methods useful when implementing Scribunto libraries. It may be loaded using

libraryUtil = require( 'libraryUtil' )

libraryUtil.checkType
Raises an error if  does not match. In addition, no error will be raised if  is nil and   is true.

is the name of the calling function, and  is the position of the argument in the argument list. These are used in formatting the error message.

libraryUtil.checkTypeMulti
Raises an error if  does not match any of the strings in the array.

This is for arguments that have more than one valid type.

libraryUtil.checkTypeForIndex
Raises an error if  does not match.

This is intended for use in implementing a  metamethod.

libraryUtil.checkTypeForNamedArg
Raises an error if  does not match. In addition, no error will be raised if  is nil and   is true.

This is intended to be used as an equivalent to  in methods called using Lua's "named argument" syntax,.

libraryUtil.makeCheckSelfFunction
This is intended for use in implementing "methods" on object tables that are intended to be called with the  syntax. It returns a function that should be called at the top of these methods with the  argument and the method name, which will raise an error if that   object is not.

This function will generally be used in a library's constructor function, something like this:

luabit
The luabit library modules "bit" and "hex" may be loaded using

bit = require( 'luabit.bit' ) hex = require( 'luabit.hex' )

Note that the bit32 library contains the same operations as "luabit.bit", and the operations in "luabit.hex" may be performed using  and.

The luabit module "noki" is not available, as it is entirely useless in Scribunto. The luabit module "utf8" is also not available, as it was considered redundant to the Ustring library.

ustring
The pure-Lua backend to the Ustring library may be loaded using

ustring = require( 'ustring' )

In all cases the Ustring library should be used instead, as that replaces many of the slower and more memory-intensive operations with callbacks into PHP code.

扩展库
Some MediaWiki extensions provide additional Scribunto libraries. These are also located in the table, usually in the table  , however, they are only present when certain extensions are installed (in addition to the Scribunto extension itself).

Such extensions use Scribunto provided hooks:
 * ScribuntoExternalLibraries
 * ScribuntoExternalLibraryPaths

Writing Scribunto libraries provides information on how such libraries can be developed to provide Lua interfaces for MediaWiki extensions.

The following libraries are planned, or are in Gerrit pending review.


 * (none at this time)

mw.wikibase
Wikibase Client provides access to localizable structured data. See Extension:Wikibase Client/Lua. This is supported by Wikidata.

mw.wikibase.lexeme
WikibaseLexeme provides access to Wikibase Lexeme entities. This is supported by Wikidata:Lexicographical data.

mw.wikibase.mediainfo
WikibaseMediaInfo provides access to Wikibase MediaInfo entities. See Extension:WikibaseMediaInfo/Lua. This is supported by Structured Data on Commons. See Commons:Structured data/Lua.

mw.bcmath
BCmath provides arbitrary-precision arithmetic to Lua modules. See BCmath documentation via "LDoc" link at Extension:BCmath.

mw.smw
Semantic Scribunto provides native support for the Scribunto extension to Semantic MediaWiki extension.

mw.ext.data
JsonConfig provides access to localizable tabular and map data. See Extension:JsonConfig/Tabular. Tabular Data and GeoJSON Map Data is supported in Commons "Data:" namespace.

mw.ext.cargo
Cargo provides a means to query its data store from Lua. See Extension:Cargo/Other features.

mw.ext.cattools
CategoryToolbox provides a means to check from Lua if a certain page belongs to a category

mw.ext.FlaggedRevs
FlaggedRevs provides a means to access the stability settings of a page from Lua.

mw.ext.TitleBlacklist
TitleBlacklist provides a means to test and obtain information about blacklisted page naming entries from Lua.

mw.ext.ParserFunctions
ParserFunctions provides a means to evaluate a parser function expressions from Lua.

mw.ext.articlePlaceholder
ArticlePlaceholder provides a means to override default Wikibase renderings from Lua. See Extension:ArticlePlaceholder/Module:AboutTopic.

改变的函数
The following functions have been modified:
 * setfenv
 * getfenv: May not be available, depending on the configuration. If available, attempts to access parent environments will fail.
 * getmetatable: Works on tables only to prevent unauthorized access to parent environments.
 * tostring: Pointer addresses of tables and functions are not provided. This is to make memory corruption vulnerabilities more difficult to exploit.
 * pairs
 * ipairs: Support for the __pairs and __ipairs metamethods (added in Lua 5.2) has been added.
 * pcall
 * xpcall: Certain internal errors cannot be intercepted.
 * require: Can fetch certain built-in modules distributed with Scribunto, as well as modules present in the Module namespace of the wiki. To fetch wiki modules, use the full page name including the namespace. Cannot otherwise access the local filesystem.

Removed functions and packages
The following packages are mostly removed. Only those functions listed are available:
 * package.*: Filesystem and C library access has been removed. Available functions and tables are:
 * package.loaded
 * package.preload
 * package.loaders: Loaders which access the local filesystem or load C libraries are not present. A loader for Module-namespace pages is added.
 * package.seeall


 * os.*: There are some insecure functions in here, such as os.execute, which can't be allowed. Available functions are:
 * os.clock
 * os.date
 * os.difftime
 * os.time


 * debug.*: Most of the functions are insecure. Available functions are:
 * debug.traceback

The following functions and packages are not available:
 * collectgarbage
 * module
 * coroutine.*: No application is known for us, so it has not been reviewed for security.
 * dofile
 * loadfile
 * io.*, file.*: Allows local filesystem access, which is insecure.
 * load
 * loadstring: These were omitted to allow for static analysis of the Lua source code. Also, allowing these would allow Lua code to be added directly to article and template pages, which was not desired for usability reasons.
 * print: This was discussed on wikitech-l and it was decided that it should be omitted in favour of return values, to improve code quality. If necessary, mw.log may be used to output information to the debug console.
 * string.dump: May expose private data from parent environments.

Additional caveats

 * Referential data structures: Circular data structures and data structures where the same node may be reached by more than one path cannot be correctly sent to PHP. Attempting to do so will cause undefined behavior. This includes (but is not limited to) returning such data structures from the module called by  and passing such data structures as parameters to Scribunto library functions that are implemented as callbacks into PHP. Such data structures may be used freely within Lua, including as the return values of modules loaded with.

Writing Scribunto libraries
This information is useful to developers writing additional Scribunto libraries, whether for inclusion in Scribunto itself or for providing an interface for their own extensions.

A Scribunto library will generally consist of five parts:


 * The PHP portion of the library.
 * The Lua portion of the library.
 * The PHP portion of the test cases.
 * The Lua portion of the test cases.
 * The documentation.

Existing libraries serve as a good example.

Library
The PHP portion of the library is a class that must extend. See the documentation for that class for implementation details. In the Scribunto extension, this file should be placed in, and a mapping added to. Other extensions should use the ScribuntoExternalLibraries hook. In either case, the key should match the Lua module name ("mw.name" for libraries in Scribunto, or "mw.ext.name" for extension libraries).

The Lua portion of the library sets up the table containing the functions that can be called from Lua modules. In the Scribunto extension, the file should be placed in. This file should generally include boilerplate something like this:

The module in  (load this with  ) contains some functions that may be helpful.

Be sure to run the Scribunto test cases with your library loaded, even if your library doesn't itself provide any test cases. The standard test cases include tests for things like libraries adding unexpected global variables. Also, if the library is loaded with PHP, any upvalues that its Lua functions have will not be reset between #invoke's. Care must be taken to ensure that modules can't abuse this to transfer information between #invoke's.

Test cases
The Scribunto extension includes a base class for test cases,, which will run the tests against both the LuaSandbox and LuaStandalone engines. The library's test case should extend this class, and should not override. In the Scribunto extension, the test case should be in  and added to the array in   (in  ); extensions should add the test case in their own   hook function, probably conditional on whether   is set.

Most of the time, all that is needed to make the test case is this:

class ClassNameTest extends Scribunto_LuaEngineTestBase { protected static $moduleName = 'ClassNameTest'; function getTestModules { return parent::getTestModules + array(             'ClassNameTest' => __DIR__ . '/ClassNameTests.lua';          ); } }

This will load the file  as if it were the page "Module:ClassNameTests", expecting it to return an object with the following properties:


 * count: Integer, number of tests
 * provide( n ): Function that returns three values:, the name of test  , and a string that is the expected output for test.
 * run( n ): Function that runs test  and returns one string.

If  is declared as shown, "Module:TestFramework" is available which provides many useful helper methods. If this is used,  would look something like this:

local testframework = require 'Module:TestFramework' return testframework.getTestProvider( {    -- Tests go here } )

Each test is itself a table, with the following properties:


 * name: The name of the test.
 * func: The function to execute.
 * args: Optional table of arguments to pass to the function.
 * expect: Results to expect.
 * type: Optional "type" of the test, default is "Normal".

The type controls the format of  and how   is called. Included types are:


 * Normal:  is a table of return values, or a string if the test should raise an error.   is simply called.
 * Iterator:  is a table of tables of return values.   is called as with an iterated for loop, and each iteration's return values are accumulated.
 * ToString: Like "Normal", except each return value is passed through.

Test cases in another extension
There are (at least) two ways to run PHPUnit tests:


 * 1) Run phpunit against core, allowing the tests/phpunit/suites/ExtensionsTestSuite.php to find the extension's tests using the UnitTestsList hook. If your extension's test class names all contain a unique component (e.g. the extension's name), the   option may be used to run only your extension's tests.
 * 2) Run phpunit against the extension directory, where it will pick up any file ending in "Test.php".

Either of these will work fine if Scribunto is loaded in LocalSettings.php. And it is easy for method #1 to work if Scribunto is not loaded, as the UnitTestsList hook can easily be written to avoid returning the Scribunto test when  is not set.

But Jenkins uses method #2. For Jenkins to properly run the tests, you will need to add Scribunto as a dependency for your extension. See for an example of how this is done.

If for some reason you need the tests to be able to run using method #2 without Scribunto loaded, one workaround is to add this check to the top of your unit test file:

Documentation
Modules included in Scribunto should include documentation in the Scribunto libraries section above. Extension libraries should include documentation in a subpage of their own extension page, and link to that documentation from the Extension libraries subsection above.

参见

 * Lua (programming language)

License
This manual is derived from the Lua 5.1 reference manual, which is available under the MIT license.

This derivative manual may also be copied under the terms of the same license.