帮助:模块/库与函数索引

来自心百科,心灵的百科全书
< 模块
Lua与模块
Lua.jpg
基础
1.Hello world
2.替换模板入门
3.function的调用
4.HTML的渲染
进阶
1.数据类型
2.字符串(string)
3.变量(variable)
4.运算符(operator)
5.分支结构(if)
6.循环结构(for/while/iterator)
7.函数(function)
8.表(table)
9.数组(table)
10.模板参数(args)
11.跨模块调用(require)
12.MongoDB函数
使用VS Code维护代码

本页面摘取常用的库和函数,供快速检索,由于全量的库和函数实在太多,如果这里搜不到可以去看MediaWiki或者Lua的官方手册。

出于以下原因,本页面内容可能会包含大量未经翻译的英文内容:

  1. 出于精确和消歧义的考虑,编程专业术语(如“string”、“boolean”)不予翻译
  2. 一些不常用的函数说明,暂时不予翻译

索引

直接用 ctrl+f 进行查找

基本函数

_G

包含当前lua脚本中全局变量(global)的table,例如某全局变量 foo 亦可以写成 _G.foo

foo = 1
mw.log( foo ) -- logs "1"
_G.foo = 2
mw.log( foo ) -- logs "2"
_G = {}       -- _G no longer points to the global variable table
_G.foo = 3
mw.log( foo ) -- still logs "2"
The global variable table may be used just like any other table. For example,

-- Call a function whose name is stored in a variable
_G[var]()

-- Log the names and stringified values of all global variables
for k, v in pairs( _G ) do
   mw.log( k, v )
end

-- Log the creation of new global variables
setmetatable( _G, {
    __newindex = function ( t, k, v )
         mw.log( "Creation of new global variable '" .. k .. "'" )
         rawset( t, k, v )
    end
} )

_VERSION

获取当前Lua的版本号

getmetatabl

getmetatable( table ) 返回一个table 的 metatable

pairs

参见:循环结构
for key, value in ipairs( t ) do
    block
end

注意,pairs返回的结果不会遵照t的排序(因为没有顺序),会按照key来进行重新排序

ipairs

参见:循环结构
for index, value in ipairs( t ) do
    block
end

next

next( table, key ) 遍历一个table中的所有key,直到key为nil或者unspecified

常用

 next( t ) == nil

来判断一个table是否包含空值

select

select( index, ... ) 配合可变长度参数(varargs)...使用

  • 当index是number的时候,返回...在index之后的所有参数
    • index可以是负值,-1从最后一位开始取
  • index是string类型的 '#'时,返回参数个数
function p.foo(v,...)
	local res = ''
	if select('#,...') == 0 then
		res = v
	else
		res = res .. ',' ..  foo(...)
	end
	return mw.dumpObject(res)
end
 
function p.test(frame)
	local res = p.foo({1,2,3,123})
	return res
end

执行{{#invoke:xxx|test}}得到结果为

table#1 {
 1,
 2,
 3,
 123,
}

type

type( value ) 以string形式返回value的类型: "nil", "number", "string", "boolean", "table", 或者 "function".

tonumber

tonumber( value, base )

tostring

tostring( value )

unpack

unpack( table, i, j ) 返回table[i], table[i+1], ···, table[j]

  • i 默认为 1
  • j 默认为 #table

Math 库

math.max

math.max( x, ... ) 返回最大值

math.min

math.min( x, ... ) 返回最小值

math.ceil

math.ceil( x ) 返回大于或等于x的最小整数

math.floor

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

模板:HuijiCollapsed

OS库

os.clock

os.clock() 返回CPU时钟

os.date

os.date( format, time ) 返回一个string,或是包含时间详细信息的table,如果未指定format参数,或者为nil,默认使用"%c"

填入的time会被format处理(参考os.time()),缺省使用当前的系统时间

  • format参数前可以 !开始(可选),例如os.date( !format, time ),使用UTC时间而非本地时间.
  • !之后,还可以通过添加*t,使函数返回一个包含详细信息的table
  • year (full)
  • month (1–12)
  • day (1–31)
  • hour (0–23)
  • min (0–59)
  • sec (0–60)
  • wday (weekday, Sunday is 1)
  • yday (day of the year)
  • isdst (daylight saving flag, boolean布尔值,可能为空)

"*t",没有被书写时,默认返回一个string

os.difftime

os.difftime( t2, t1 ) 返回t1、t2之间的秒数差

os.time

os.time( table ) 返回一个number,代表当前的时间

  • 没有参数时,返回当前时间
  • 参数是table时,编码为table的时间格式会被解析,table必需包含"year"、 "month"、 和 "day",可以包含"hour" (default 12)、 "min" (default 0)、"sec" (default 0), 和 "isdst"。

Package库

require

require( modulename )

参考:help:模块/跨模块调用

package.loaded

一个table,记录了所有已通过require加载的内容。require前会先检查目标是否已在package.loaded中,若存在则直接调用,以保证每个模块只会生成一次。

  • 但会把'Module:T', 'Module:t', 'module:T'视为不同的模块

package.loaded内的数据不会在invoke结束时回收,可通过如下操作手动清理

for k,_ in pairs(package.loaded) do
    package.loaded[k] = nil
end

String库

<callout>由于String库无法处理UTF-8字符,所以我们推荐直接使用由MediaWiki提供的Ustring库</callout>

Ustring库

模板:ScribuntoOnly

mw.ustring.find

mw.ustring.find( s, pattern, init, plain ) 在s(string)中,查找第一个匹配的pattern(参考#Ustring patterns),返回匹配结果的开始和结束位置,没有匹配返回nil。

  • 当pattern中书写了capture时,返回捕获的字符串
  • init为起始位置,默认为1,可以为负值
  • plain为模式开关,开启后pattern中的表达式不再具有magic words的性质,仅按照字符匹配,注意,书写plain时(第四参数),init(第三参数)不能缺省。

mw.ustring.gsub

mw.ustring.gsub( s, pattern, repl, n ) 返回一个被修改过的s(string类型)复制,其中前n个(缺省为1)匹配的pattern(参考#Ustring patterns)将会被repl替换。

  • 当repl为string类型时,可以通过添加%作为escape符号(类似正则表达式中的\),repl中的“%n”(n为1~9)表示是第n个被捕捉到(如果有捕捉行为的话)的字符串(类似正则表达式中的$1$2……),%0表示全部匹配,%%表示一个“%”
  • 当repl是table类型时,每次匹配时都会查询这个table。如果pattern中有捕捉行为(capture),则用第一次捕捉到的内容作为key来查询table。如果pattern中没有捕捉行为,则用整个匹配项作为key在table中查询。
  • 当repl是个function时,每次匹配时都会唤起这个程序,如果pattern中有捕捉行为(capture),所有被捕捉到的字符串会作为该function的参数(按照顺序)。如果pattern中没有捕捉行为,则用整个匹配项作为一整个参数被传入该function。
  • table和function的返回值为string或number类型时,会作为替代部分生效,其他情况下,会返回false或者nil,不会产生替换行为。

mw.ustring.len

mw.ustring.len( s ) 以codepoints形式返回字符串的长度,不合法的UTF-8字符返回nil

mw.ustring.lower

mw.ustring.lower( s ) s转换成小写

mw.ustring.upper

mw.ustring.upper( s ) 将s转换成大写字母

mw.ustring.match

mw.ustring.match( s, pattern, init ) 试图在s(string类型)中寻找pattern(参考#Ustring patterns),在没有捕捉表达式的情况下返回整个匹配,如果有则返回捕捉到的内容,否则返回nil。。

  • 第三个参数init默认为1,可以为负值

mw.ustring.sub

mw.ustring.sub( s, i, j ) 返回s(string类型)中从位置i开始到j为止的部分,

  • i , j 可以为负数
  • 如果 j 没有指定,则默认为 -1

mw.ustring.rep

mw.ustring.rep( s, n ) 重复s(string)n遍

mw.ustring.byte

mw.ustring.byte( s, i, j ) 将s(string类型)视为字节的集合,返回一个table,内容为 s[i], s[i+1], ···, s[j].

  • i 默认为 1
  • j 默认为 i

mw.ustring.gmatch

mw.ustring.gmatch( s, pattern ) 返回一个迭代器(iterator),每次调用时,返回s(string类型)中的下一个pattern(参考#Ustring patterns)的匹配。

  • pattern中的'^' 不会被视为magic word

模板:HuijiCollapsed


Ustring patterns

参考:匹配式(Patterns)

Ustring Patterns的规则和语法简述:

  • %a: 代表所有属于"Letter"的字符
  • %c: 代表所有属于"Control"的字符
  • %d: 代表所有属于"Number, decimal digit"的字符
  • %l: 代表所有属于"Lowercase Letter"的字符
  • %p: 代表所有属于"Punctuation"的字符
  • %s: 代表所有属于"Separator"的字符,以及tab, linefeed, carriage return, vertical tab, 和 form feed.
  • %u: 代表所有属于"Uppercase Letter"的字符
  • %w: 代表所有属于 "Letter" 或 "Decimal Number"的字符
  • %x: adds fullwidth character versions of the hex digits.

A, %C, %D, %L, %P, %S, %U和%W 表示上述的补集。

In all cases, characters are interpreted as Unicode characters instead of bytes, so ranges such as [0-9], patterns such as %b«», and quantifiers applied to multibyte characters will work correctly. Empty captures will capture the position in code points rather than bytes.

Text 库

模板:ScribuntoOnly 本库的函数兼容 UTF-8 字符

mw.text.split

mw.text.split( s, pattern, plain ) 将string类型的s按照pattern(参见#Ustring patterns)进行拆解,返回一个包含每一段字符串的table

例如

mw.text.split( 'a b\tc\nd', '%s' )

返回结果如下:

{ 'a', 'b', 'c', 'd' }

如果pattern的匹配项是空字符"",那么会把s逐个字母拆开。

mw.text.gsplit

mw.text.gsplit( s, pattern, plain )

mw.text.split()完全一致,区别是返回一个迭代器而不是table

mw.text.tag

mw.text.tag( name, attrs, content )

mw.text.tag{ name = string, attrs = table, content = string|false }

生成一个HTML风格的tag(以及属性)

If attrs 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 content is not given (or is nil), only the opening tag is returned. If content 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 <ref>, use frame:extensionTag() instead.

mw.text.trim

mw.text.trim( s )

mw.text.trim( s, charset )

将string类型的s中,位于开始和结束部分的空格或者其他字符移除

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

mw.text.truncate

mw.text.truncate( text, length )

mw.text.truncate( text, length, ellipsis )

mw.text.truncate( text, length, ellipsis, adjustLength )

将指定的string类型s,按照length长度缩写,被缩写的部分默认为“...”,可以单独指定ellipsis参数作为缩略部分。adjustLength参数给出后,被缩写的字符串和ellipsis加在一起不会超过这个长度。

以默认的"..." 作为ellipsis,实际演示如下:

-- Returns "foobarbaz"
mw.text.truncate( "foobarbaz", 9 )

-- Returns "fooba..."
mw.text.truncate( "foobarbaz", 5 )

-- Returns "...arbaz"
mw.text.truncate( "foobarbaz", -5 )

-- Returns "foo..."
mw.text.truncate( "foobarbaz", 6, nil, true )

-- Returns "foobarbaz", because that's shorter than "foobarba..."
mw.text.truncate( "foobarbaz", 8 )

mw.text.jsonDecode

mw.text.jsonDecode( s )

mw.text.jsonDecode( s, flags )

对JSON字符串进行解码,返回lua的table

  • flags is 0 or a combination (use +) of the flags mw.text.JSON_PRESERVE_KEYS and mw.text.JSON_TRY_FIXING.

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

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

Limitations:

  • 包含空值的key会被扔掉,转换完成的table可能和JSON长得不太一样
  • 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 mw.text.JSON_PRESERVE_KEYS is used.

mw.text.jsonEncode

mw.text.jsonEncode( value )

mw.text.jsonEncode( value, flags )

将lua的table编码为JSON。Errors are raised if the passed value cannot be encoded in JSON. flags is 0 or a combination (use +) of the flags mw.text.JSON_PRESERVE_KEYS and mw.text.JSON_PRETTY.

Normally Lua one-based sequence tables are encoded as JSON zero-based arrays; when mw.text.JSON_PRESERVE_KEYS is set in flags, 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 __pairs 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

mw.text.JSON_PRESERVE_KEYS 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

mw.text.killMarkers( s )

移除文本中的所有MediaWiki标记语言

mw.text.listToText

mw.text.listToText( list )

mw.text.listToText( list, separator, conjunction )

类似table.concat() ,将一个list展开为字符串

 -- Returns the empty string
 mw.text.listToText( {} )
 
 -- Returns "1"
 mw.text.listToText( { 1 } )
 
 -- Returns "1 and 2"
 mw.text.listToText( { 1, 2 } )
 
 -- Returns "1, 2, 3, 4 and 5"
 mw.text.listToText( { 1, 2, 3, 4, 5 } )
 
 -- Returns "1; 2; 3; 4 or 5"
 mw.text.listToText( { 1, 2, 3, 4, 5 }, '; ', ' or ' )

mw.text.nowiki

mw.text.nowiki( s ) 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.unstripNoWiki

mw.text.unstripNoWiki( s )

Replaces MediaWiki <nowiki> strip markers with the corresponding text. Other types of strip markers are not changed.

mw.text.unstrip

mw.text.unstrip( s )

等价于 mw.text.killMarkers( mw.text.unstripNoWiki( s ) ).

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

Table库

table.concat

table.concat( table, sep, i, j ) 将一个table类型的数据按照sep作为分隔符的方式进行转换:返回table[i] .. sep .. table[i+1] ··· sep .. table[j].

  • i 的默认值是 1
  • j 的默认值是#table(length)
  • 如果i > j 返回空的string

table.insert

table.insert( table, value )

table.insert( table, pos, value ) 将指定的value插入table,pos是位置,默认为#table+1(相当于python中的append)

table.maxn

table.maxn( table ) 范围table中最大的正数序号(元素个数),大致上等价于:

function table.maxn( table )
    local maxn, k = 0, nil
    repeat
        k = next( table, k )
        if type( k ) == 'number' and k > maxn then
            maxn = k
        end
    until not k
    return maxn
end

table.remove

table.remove( table, pos ) 将table中指定pos位置的元素移除,并将其他元素向空缺处平移。pos的默认值为#table,table.remove( t ) 会移除t的最后一个元素

table.sort

table.sort( table, comp ) 将table元素从table[1] 到table[#table] 进行排序, If comp 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 not comp(a[i+1],a[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.

Scribunto 基础库

模板:ScribuntoOnly

mw.loadData

mw.loadData( module )

有时模块中需要使用大量table数据,例如一个单位换算的模块会需要使用大量关于单位间换算关系的数据。而这些模块可能会在同一个页面中被多次调用,如果每次{{#invoke:}}时都重新加载数据会消耗较多时间。mw.loadData()便可用于解决该问题。

mw.loadData()用法类似于require(),但有以下差别:

  • 引用的模块在每个页面仅加载一次,而不是每次{{#invoke:}}时均加载
  • 引用的模块不会记录在#package.loaded
  • 引用的模块的返回值必须为table
  • 返回的table及其子table中只能包含boolean、number、string、table类型的数据,不能包含function
  • 返回的table及其子table不能拥有metatable
  • 返回的table及其子table的键值(key)只能为boolean、number、string类型
  • 实际获得的table是只读的,pairs()、ipairs()可用,但#、next()及table库中的方法均无法正常生效
  • 对于上面举例的单位换算模块,可以把代码放在"Module:Convert"中,数据放在"Module:Convert/data"中,在"Module:Convert"内通过local data = mw.loadData( 'Module:Convert/data' )来高效加载数据
  • 补充:通过mw.loadData加载太多数据可能会导致程序内存不足


mw.dumpObject

mw.dumpObject( object )

Serializes object to a human-readable representation, then returns the resulting string.

mw.log

mw.log( args )

Passes the arguments to mw.allToString(), then appends the resulting string to the log buffer. In the debug console, the function print() is an alias for this function.

  • mw.log()可以输入多个参数,中间通过“,”隔开。例如
mw.log('a','b',1)
-> a b 1
  • mw.log只能输出非table类型的变量,table类型的变量应该使用mw.dumpObject()或者mw.logObject()

mw.logObject

mw.logObject( object )

mw.logObject( object, prefix )

Calls mw.dumpObject() and appends the resulting string to the log buffer. If prefix 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 object

模板:ScribuntoOnly invoke时作为参数传入,也可通过mw.getCurrentFrame()获取。

frame.args

A table for accessing the arguments passed to the frame. For example, if a module is called from wikitext with

{{#invoke:module|function|arg1|arg2|name=arg3}}

then frame.args[1] will return "arg1", frame.args[2] will return "arg2", and frame.args['name'] (or frame.args.name) will return "arg3". It is also possible to iterate over arguments using pairs( frame.args ) or ipairs( frame.args ). However, due to how Lua implements table iterators, iterating over arguments will return them in an unspecified order, and there's no way to know the original order as they appear in wikitext.

Note that values in this table are always strings; tonumber() may be used to convert them to numbers, if necessary. Keys, however, are numbers even if explicitly supplied in the invocation: {{#invoke:module|function|1|2=2}} gives string values "1" and "2" indexed by numeric keys 1 and 2.

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, frame.args 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 #frame.args, next( frame.args ), 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 <pre>, <nowiki>, <gallery> and <ref>, 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:getParent

frame:getParent()获取调用链的上一级frame对象,若不存在则返回nil

例如在wikitext中调用模板A,在模板A中调用模块B,则模块B收到的frame.args中包含A传入B的参数,frame:getParent().args中包含wikitext传入A的参数。

frame:callParserFunction

frame:callParserFunction( name, args )

frame:callParserFunction( name, ... )

frame:callParserFunction{ name = string, args = table }

Note the use of named arguments. Call a parser function, returning an appropriate string. Whenever possible, native Lua functions or Scribunto library functions should be preferred to this interface.

The following calls are approximately equivalent to the indicated wikitext:

-- {{ns:0}}
frame:callParserFunction{ name = 'ns', args = 0 }
-- {{#tag:nowiki|some text}}
frame:callParserFunction{ name = '#tag', args = { 'nowiki', 'some text' } }
frame:callParserFunction( '#tag', { 'nowiki', 'some text' } )
frame:callParserFunction( '#tag', 'nowiki', 'some text' )
frame:callParserFunction( '#tag:nowiki', 'some text' )
-- {{#tag:ref|some text|name=foo|group=bar}}
frame:callParserFunction{ name = '#tag:ref', args = {
    'some text', name = 'foo', group = 'bar'
} }

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 = title, args = table }

Note the use of named arguments. This is transclusion. The call

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

does roughly the same thing from Lua that {{template|arg1|arg2|name=arg3}} does in wikitext. As in transclusion, if the passed title does not contain a namespace prefix it will be assumed to be in the Template: namespace.

Note that the title and arguments are not preprocessed before being passed into the template:

-- This is roughly equivalent to wikitext like {{template|{{!}}}}
frame:expandTemplate{ title = 'template', args = { '|' } }
-- This is roughly equivalent to wikitext like {{template|{{((}}!{{))}}}}
frame:expandTemplate{ title = 'template', args = { '{{!}}' } }
frame:extensionTag[edit]
frame:extensionTag( name, content, args )
frame:extensionTag{ name = string, content = string, args = table_or_string }

This is equivalent to a call to frame:callParserFunction() with function name '#tag:' .. name and with content prepended to args.

-- These are equivalent
frame:extensionTag{ name = 'ref', content = 'some text', args = { name = 'foo', group = 'bar' } }
frame:extensionTag( 'ref', 'some text', { name = 'foo', group = 'bar' } )

frame:callParserFunction{ name = '#tag:ref', args = {
    'some text', name = 'foo', group = 'bar'
} }
-- These are equivalent
frame:extensionTag{ name = 'ref', content = 'some text', args = 'some other text' }
frame:callParserFunction{ name = '#tag:ref', args = {
    'some text', 'some other text'
} }
frame:getParent[edit]
frame:getParent()

Called on the frame created by {{#invoke:}}, returns the frame for the page that called {{#invoke:}}. Called on that frame, returns nil.

For instance, if the template {{Example}} contains the code {{#invoke:ModuleName}}, and a page transcludes that template and supplies arguments to it (模板:Example), calling mw.getCurrentFrame():getParent().args[1], mw.getCurrentFrame():getParent().args[2] in Module:ModuleName will return "arg1", "arg2".

frame:getTitle

frame:getTitle()

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

frame:newChild

frame:newChild{ title = title, args = table }

Note the use of named arguments. 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 {{#invoke:}}. The number of frames that may be created at any one time is limited.

frame:preprocess

frame:preprocess( string )

frame:preprocess{ text = string }

This expands wikitext in the context of the frame, i.e. templates, parser functions, and parameters such as {{{1}}} are expanded. Certain special tags written in XML-style notation, such as <pre>, <nowiki>, <gallery> and <ref>, will be replaced with "strip markers" — special strings which begin with a delete character (ASCII 127), to be replaced with HTML after they are returned from #invoke.

If you are expanding a single template, use frame:expandTemplate 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 frame:callParserFunction for the same reasons.

frame:preprocess(mw.title.new(title):getContent())获取一个页面parse后的内容。

frame:getArgument

frame:getArgument( arg )

frame:getArgument{ name = arg }

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

The returned object has one method, object:expand(), that returns the expanded wikitext for the argument.

frame:newParserValue

frame:newParserValue( text )

frame:newParserValue{ text = text }

Returns an object with one method, object:expand(), that returns the result of frame:preprocess( text ).

frame:newTemplateParserValue

frame:newTemplateParserValue{ title = title, args = table }

Note the use of named arguments. Returns an object with one method, object:expand(), that returns the result of frame:expandTemplate called with the given arguments.

frame:argumentPairs

frame:argumentPairs()

Same as pairs( frame.args ). Included for backwards compatibility.

HTML 库

模板:ScribuntoOnly 中文文档见帮助:模块/HTML编写入门#mw.html库

mw.html.create

mw.html.create( tagName, args )

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

args can be a table with the following keys:

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

mw.html:node

html:node( builder )

Appends a child mw.html (builder) node to the current mw.html instance. If a nil parameter is passed, this is a no-op. A (builder) node is a string representation of an html element.

mw.html:wikitext[edit] 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

html:newline()

Appends a newline to the mw.html object.

mw.html:tag

html:tag( tagName, args )

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

mw.html:attr

html:attr( name, value )

html:attr( table )

Set an HTML attribute with the given name and value 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

html:getAttr( name )

Get the value of a html attribute previously set using html:attr() with the given name.

mw.html:addClass

html:addClass( class )

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

mw.html:css

html:css( name, value )

html:css( table )

Set a CSS property with the given name and value 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

html:cssText( css )

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

mw.html:done

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

html:allDone()

Like html:done(), but traverses all the way to the root node of the tree and returns it.

Language 库

模板:ScribuntoOnly 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 mw.language.name are available on the global mw.language table; functions documented as mw.language:name and lang:name are methods of a language object (see mw.language.new or mw.language.getContentLanguage).

mw.language.fetchLanguageName

mw.language.fetchLanguageName( code, inLanguage )

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

mw.language.fetchLanguageNames

mw.language.fetchLanguageNames()

mw.language.fetchLanguageNames( inLanguage )

mw.language.fetchLanguageNames( inLanguage, include )

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 inLanguage returns all names in that language.

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

mw.language.getContentLanguage

mw.language.getContentLanguage()

mw.getContentLanguage()

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

mw.language.getFallbacksFor

mw.language.getFallbacksFor( code )

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

mw.language.isKnownLanguageTag

mw.language.isKnownLanguageTag( code )

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 mw.language.isValidBuiltInCode) and returns a non-empty string for mw.language.fetchLanguageName.

mw.language.isSupportedLanguage

mw.language.isSupportedLanguage( code )

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 mw.language.isValidCode), 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 mw.language.isKnownLanguageTag). Also note that certain codes are "supported" despite mw.language.isValidBuiltInCode returning false.

mw.language.isValidBuiltInCode

mw.language.isValidBuiltInCode( code )

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 mw.language.isValidCode); 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 mw.language.isSupportedLanguage) even though this function returns false.

mw.language.isValidCode

mw.language.isValidCode( code )

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

mw.language.new( code )

mw.getLanguage( code )

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

lang:getCode()

Returns the language code for this language object.

mw.language:getFallbackLanguages

lang:getFallbackLanguages()

Returns a list of MediaWiki's fallback language codes for this language object. Equivalent to mw.language.getFallbacksFor( lang:getCode() ).

mw.language:isRTL

lang:isRTL()

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

mw.language:lc

lang:lc( s )

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.getContentLanguage():lc( s ).

mw.language:lcfirst

lang:lcfirst( s )

Converts the first character of the string to lowercase, as with lang:lc().

mw.language:uc

lang:uc( s )

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.getContentLanguage():uc( s ).

mw.language:ucfirst

lang:ucfirst( s )

Converts the first character of the string to uppercase, as with lang:uc().

mw.language:caseFold

lang:caseFold( s ) 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

lang:formatNum( n )

lang:formatNum( n, options )

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 options is a table of options, which can be:

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

lang:formatDate( format, timestamp, local )

Formats a date according to the given format string. If timestamp is omitted, the default is the current time. The value for local 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 timestamp 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:

-- This string literal contains a newline, not the two characters "\n", so it is not equivalent to {{#time:\n}}.
lang:formatDate( '\n' )
-- This is equivalent to {{#time:\n}}, not {{#time:\\n}}.
lang:formatDate( '\\n' )
-- This is equivalent to {{#time:\\n}}, not {{#time:\\\\n}}.
lang:formatDate( '\\\\n' )

mw.language:formatDuration

lang:formatDuration( seconds )

lang:formatDuration( seconds, allowedIntervals )

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.

allowedIntervals, 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

lang:parseFormattedNumber( s )

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

mw.language:convertPlural

lang:convertPlural( n, ... )

lang:convertPlural( n, forms )

lang:plural( n, ... )

lang:plural( n, forms )

This chooses the appropriate grammatical form from forms (which must be a sequence table) or ... based on the number n. For example, in English you might use n .. ' ' .. lang:plural( n, 'sock', 'socks' ) or n .. ' ' .. lang:plural( n, { 'sock', 'socks' } ) 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

lang:convertGrammar( word, case )

lang:grammar( case, word )

Note the different parameter order between the two aliases. convertGrammar matches the order of the method of the same name on MediaWiki's Language object, while grammar matches the order of the parser function of the same name, documented at Special:MyLanguage/Help:Magic words#Localisation. This chooses the appropriate inflected form of word for the given inflection code case.

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

mw.language:gender

lang:gender( what, masculine, feminine, neutral )

lang:gender( what, { masculine, feminine, neutral } )

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

mw.language:getArrow

lang:getArrow( direction )

Returns a Unicode arrow character corresponding to direction:

  • 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

lang:getDir()

Returns "ltr" or "rtl", depending on the directionality of the language.

mw.language:getDirMark

lang:getDirMark( opposite )

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 opposite is a true or false value.

mw.language:getDirMarkEntity

lang:getDirMarkEntity( opposite )

Returns "‎" or "‏", depending on the directionality of the language and whether opposite is a true or false value.

mw.language:getDurationIntervals

lang:getDurationIntervals( seconds )

lang:getDurationIntervals( seconds, allowedIntervals )

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.

allowedIntervals, 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'.

Message 库

模板:ScribuntoOnly This library is an interface to the localisation messages and the MediaWiki: namespace.

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

mw.message.new

mw.message.new( key, ... )

Creates a new message object for the given message key.

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

mw.message.newFallbackSequence

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

mw.message.newRawMessage( msg, ... )

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 params() method.

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

mw.message.rawParam

mw.message.rawParam( value )

Wraps the value so that it will not be parsed as wikitext by msg:parse().

mw.message.numParam

mw.message.numParam( value )

Wraps the value so that it will automatically be formatted as by lang:formatNum(). Note this does not depend on the Language library actually being available.

mw.message.getDefaultLanguage

mw.message.getDefaultLanguage()

Returns a Language object for the default language.

mw.message:params

msg:params( ... )

msg:params( 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 msg object, to allow for call chaining.

mw.message:rawParams

msg:rawParams( ... )

msg:rawParams( params )

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

Returns the msg object, to allow for call chaining.

mw.message:numParams

msg:numParams( ... )

msg:numParams( params )

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

Returns the msg object, to allow for call chaining.

mw.message:inLanguage

msg:inLanguage( lang )

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

The default language is the one returned by mw.message.getDefaultLanguage().

Returns the msg object, to allow for call chaining.

mw.message:useDatabase

msg:useDatabase( bool )

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 msg object, to allow for call chaining.

mw.message:plain

msg:plain()

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

mw.message:exists

msg:exists()

Returns a boolean indicating whether the message key exists.

mw.message:isBlank

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

msg: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 "-".

Site 库

模板:ScribuntoOnly

mw.site.currentVersion

A string holding the current version of MediaWiki.

mw.site.scriptPath

The value of $wgScriptPath.

mw.site.server

The value of $wgServer.

mw.site.siteName

The value of $wgSitename.

mw.site.stylePath

The value of $wgStylePath.

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 mw.site.namespaces[4] and mw.site.namespaces.Project 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

mw.site.stats.pagesInCategory( category, which )

This function is expensive

Gets statistics about the category. If which 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 which 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

mw.site.stats.pagesInNamespace( ns )

Returns the number of pages in the given namespace (specify by number).

mw.site.stats.usersInGroup

mw.site.stats.usersInGroup( group )

Returns the number of users in the given group.

mw.site.interwikiMap

mw.site.interwikiMap( filter )

Returns a table holding data about available interwiki prefixes. If filter is the string "local", then only data for local interwiki prefixes is returned. If filter 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 $wgExtraInterlanguageLinkPrefixes.
  • 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.

Semantic Scribunto (SMW)

模板:SemanticScribuntoOnly

mw.smw.ask

-- Module:SMW
local p = {}

-- Return results
function p.ask(frame)

    if not mw.smw then
        return "mw.smw module not found"
    end

    if frame.args[1] == nil then
        return "no parameter found"
    end

    local queryResult = mw.smw.ask( frame.args )

    if queryResult == nil then
        return "(no values)"
    end

    if type( queryResult ) == "table" then
        local myResult = ""
        for num, row in pairs( queryResult ) do
            myResult = myResult .. '* This is result #' .. num .. '\n'
            for property, data in pairs( row ) do
                local dataOutput = data
                if type( data ) == 'table' then
                    dataOutput = mw.text.listToText( data, ', ', ' and ')
                end
                myResult = myResult .. '** ' .. property .. ': ' .. dataOutput .. '\n'
            end
        end
        return myResult
    end

    return queryResult
end

-- another example, ask used inside another function
function p.inlineAsk()

    local entityAttributes = {
        'has name=name',
        'has age=age',
        'has color=color'
    }
    local category = 'thingies'
    
    -- build query
    local query = {}
    table.insert(query, '[[Category:' .. category .. ']]')
    
    for _, v in pairs( entityAttributes ) do
        table.insert( query, '?' .. v )
    end
    
    query.mainlabel = 'origin'
    query.limit = 10
    
    local result = mw.smw.ask( query )
    
    local output = ''
    if result and #result then
    
        for num, entityData in pairs( result ) do
            -- further process your data
            output = output .. entityData.origin .. ' (' .. num .. ') has name ' .. entityData.name
                .. ', color ' .. entityData.color .. ', and age ' .. entityData.age
        end
    end
    
    return output
end

return p
Return format
The return format is a simple collection of tables (one per result set) holding your smw data, each indexed by property names or labels respectively. You can see an example below:

-- assuming sample call
local result = mw.smw.ask( '[[Modification date::+]]|?#-=page|?Modification date|?Last editor is=editor|?page author=authors|limit=2|mainlabel=-' )
-- same as
local result = mw.smw.ask{
    '[[Modification date::+]]', '?#-=page', '?Modification date', '?Last editor is=editor', '?page author#-=authors', 
    limit = 2, mainlabel = '-'
} 
-- your result would look something like
{
    {
        ['Modification date'] = '1 January 1970 23:59:59',
        authors = {
            'User:Mwjames', 'User:Oetterer'
        },
        editor = '[[:User:Mwjames|User:Mwjames]]',
        page = 'Main page'
    },
    {
        ['Modification date'] = '2 January 1970 00:00:42',
        authors = 'User:Oetterer',
        editor = '[[:User:Oetterer|User:Oetterer]]',
        page = 'User:Oetterer'
    },
}
-- please note the unlinking of properties 'page authors', and mainlabel '?' by using the #- operator
-- note also: unlinking via parameter link is not supported at this point

mw.smw.getPropertyType

The function mw.smw.getPropertyType provides an easy way to get the type of a given property. Note however, that it uses the smw internal property types, not the one you might be used to.

-- Module:SMW
local p = {}

-- Return property type
function p.type(frame)

    if not mw.smw then
        return "mw.smw module not found"
    end

    if frame.args[1] == nil then
        return "no parameter found"
    end
    local pType = mw.smw.getPropertyType( frame.args[1] )

    if pType == nil then
        return "(no values)"
    end

    return pType
end

return p

{{#invoke:smw|type|Modification date}} can be used as it returns a simple string value such as _dat.

mw.smw.getQueryResult

With mw.smw.getQueryResult you can execute an smw query. It returns the result as a lua table for direct use in modules. For available parameters, please consult the Semantic Media Wiki documentation hub.

Please see the return format below for the difference between this and mw.smw.ask.

This is a sample call:

-- Module:SMW
local p = {}

-- Return results
function p.ask(frame)

    if not mw.smw then
        return "mw.smw module not found"
    end

    if frame.args[1] == nil then
        return "no parameter found"
    end

    local queryResult = mw.smw.getQueryResult( frame.args )

    if queryResult == nil then
        return "(no values)"
    end

    if type( queryResult ) == "table" then
        local myResult = ""
        for k,v in pairs( queryResult.results ) do
            if  v.fulltext and v.fullurl then
                myResult = myResult .. k .. " | " .. v.fulltext .. " " .. v.fullurl .. " | " .. "<br/>"
            else
                myResult = myResult .. k .. " | no page title for result set available (you probably specified ''mainlabel=-')"
            end
        end
        return myResult
    end

    return queryResult
end

return p

Return format The return format matches the data structure delivered by the api. You can see an example below:

-- assuming sample call
local result = mw.smw.getQueryResult( '[[Modification date::+]]|?Modification date|?Last editor is=editor|limit=2|mainlabel=page' )
-- your result would look something like
{
    printrequests = {
        {
            label = 'page',
            redi = null,
            typeid = '_wpg',
            mode = 2,
            format = null
        },
        {
            label = 'Modification date',
            key = '_MDAT',
            redi = null,
            typeid = '_dat',
            mode = 1,
            format = null
        },
        {
            label = 'editor',
            key = '_LEDT',
            redi = null,
            typeid = '_wpg',
            mode = 1,
            format = null
        },
    },
    results = {
        {
            printouts = {
                ['Modification date'] = {
                    {
                        timestamp = 123456789, -- a unix timestamp
                        raw = '1/1970/1/1/23/59/59/0'
                    }
                },
                editor = {
                    {
                        fulltext = 'User:Mwjames',
                        fullurl = 'https://your.host/w/User:Mwjames'
                    }
                }
            },
            fulltext = 'Main page',
            fullurl = 'https://your.host/w/Main_page',
            namespace = 0,
            exist = 1,
            displaytitle = ''
        },
        {
            printouts = {
                ['Modification date'] = {
                    {
                        timestamp = 123456790, -- a unix timestamp
                        raw = '1/1970/1/2/0/0/1/0'
                    }
                },
                editor = {
                    {
                        fulltext = 'User:Matthew-a-thompson',
                        fullurl = 'https://your.host/w/User:Matthew-a-thompson'
                    }
                }
            },
            fulltext = 'User:Matthew A Thompson',
            fullurl = 'https://your.host/w/User:Matthew_A_Thompson',
            namespace = 2,
            exist = 1,
            displaytitle = ''
        },
    },
    serializer = 'SMW\Serializers\QueryResultSerializer',
    version = 0.11,
    meta = {
        hash = '5b2187c3df541ca08d378b3690a31173',
        count = 2,  -- number of results
        offset = 0, -- used offset
        source = null,
        time = 0.000026,
    }
}

Calling {{#invoke:smw|ask|[[Modification date::+]]|?Modification date|limit=0|mainlabel=-}} only makes sense in a template or another module that can handle table return values.

mw.smw.set

This makes the smw parser function #set available in lua and allows you to store data in your smw store. The usage is similar to that of the parser function, however be advised to read the notes under the example.

This is a sample call:

-- Module:SMW
local p = {}

-- set with return results
function p.set( frame )

    if not mw.smw then
        return "mw.smw module not found"
    end

    local result = mw.smw.set( frame.args )
    if result == true then
        return 'Your data was stored successfully'
    else
        return 'An error occurred during the storage process. Message reads ' .. result.error
    end
end

-- another example, set used inside another function
function p.inlineSet( frame )

    local dataStoreTyp1 = {}

    dataStoreTyp1['my property1'] = 'value1'
    dataStoreTyp1['my property2'] = 'value2'
    dataStoreTyp1['my property3'] = 'value3'

    local result = mw.smw.set( dataStoreTyp1 )

    if result == true then
        -- everything ok
    else
        -- error message to be found in result.error
    end

    local dataStoreType2 = {
        'my property1=value1',
        'my property2=value2',
        'my property3=value3',
    }

    local result = mw.smw.set( dataStoreType2 )

    if result == true then
        -- everything ok
    else
        -- error message to be found in result.error
    end
    
    local dataStoreType3 = {
        ['my property'] = {
            'value1',
            'value2',
            'value3'
        }
    }

    local result = mw.smw.set( dataStoreType3 )

    if result == true then
        -- everything ok
    else
        -- error message to be found in result.error
    end
end

return p

As you can see, you can supply arguments to mw.smw.set as either an associative array and as lua table. Also, if you want to supply multiple values for a property, you can use a subtable for the values (see example using dataStoreType3).

Note however: lua does not maintain the order in an associative array. Using parameters for set like the separator or the template parameter requires a strict parameter order in which case you must use the table format as shown with dataStoreType2 in the example above.

SMW.set can be invoked via {{#invoke:smw|set|my property1=value1|my property2=value2}}. However, using the lua function in this way makes little sense. It is designed to be used inside your modules.

mw.smw.subobject

This makes the smw parser function #subobject available in lua and allows you to store data in your smw store as subobjects. The usage is similar to that of the parser function but be advised to read the notes for mw.smw.info as well.

This is a sample call:

-- Module:SMW
local p = {}

-- subobject with return results
function p.subobject( frame )

    if not mw.smw then
        return "mw.smw module not found"
    end

    if #frame.args == 0 then
        return "no parameters found"
    end
    local result = mw.smw.subobject( frame.args )
    if result == true then
        return 'Your data was stored successfully in a subobject'
    else
        return 'An error occurred during the subobject storage process. Message reads ' .. result.error
    end
end
-- another example, subobject used inside another function
function p.inlineSubobject( frame )

    local dataStoreTyp1 = {}

    dataStoreTyp1['my property1'] = 'value1'
    dataStoreTyp1['my property2'] = 'value2'
    dataStoreTyp1['my property3'] = 'value3'

    local result = mw.smw.subobject( dataStoreTyp1 )

    if result == true then
        -- everything ok
    else
        -- error message to be found in result.error
    end

    local dataStoreType2 = {
        'my property1=value1',
        'my property2=value2',
        'my property3=value3',
    }

    local result = mw.smw.subobject( dataStoreType2 )

    if result == true then
        -- everything ok
    else
        -- error message to be found in result.error
    end

    -- you can also manually set a subobject id. however, this is not recommended

    local result = mw.smw.subobject( dataStoreType2, 'myPersonalId' )
    if result == true then
        -- everything ok
    else
        -- error message to be found in result.error
    end

    local dataStoreType3 = {
        ['my property'] = {
            'value1',
            'value2',
            'value3'
        }
    }

    local result = mw.smw.subobject( dataStoreType3 )

    if result == true then
        -- everything ok
    else
        -- error message to be found in result.error
    end
end

return p

mw.smw.info

This makes the smw parser function #info available in lua and allows you to add tooltips to your output stream. See the documentation on the SMW homepage for more information.

This is a sample call:

-- Module:SMW
local p = {}

-- set with direct return results
function p.info( frame )

    if not mw.smw then
        return "mw.smw module not found"
    end

    if frame.args[1] == nil then
        return "no parameter found"
    end

    local tooltip
    if frame.args[2] then
        tooltip = mw.smw.info( frame.args[1], frame.args[2] )
    else
        tooltip = mw.smw.info( frame.args[1] )
    end

    return tooltip
end
-- another example, info used inside another function
function p.inlineInfo( frame )

    local output = 'This is sample output'

    -- so some stuff

    output = output .. mw.smw.info( 'This is a warning', 'warning' )

    -- some more stuff

    return output
end

return p