### Scribunto Lua Library Setup Source: https://www.mediawiki.org/wiki/Extension:Scribunto/Lua_reference_manual This Lua code snippet demonstrates the boilerplate for setting up a Scribunto library, including interface setup, PHP callback integration, and global namespace management. It ensures proper loading and makes the library available under the `mw.ext` namespace. ```lua local object = {} local php function object.setupInterface( options ) -- Remove setup function object.setupInterface = nil -- Copy the PHP callbacks to a local variable, and remove the global php = mw_interface mw_interface = nil -- Do any other setup here -- Install into the mw global mw = mw or {} mw.ext = mw.ext or {} mw.ext.NAME = object -- Indicate that we're loaded package.loaded['mw.ext.NAME'] = object end return object ``` -------------------------------- ### Lua Local Variable Scope Example Source: https://www.mediawiki.org/wiki/Extension:Scribunto/Lua_reference_manual Demonstrates the scope of a local variable, showing that its visibility starts after declaration and extends to the end of the block. ```lua local x = 5 print(x) -- x is visible here do local y = x + 1 print(y) -- y is visible here end -- print(y) -- This would cause an error, y is out of scope ``` -------------------------------- ### Get MediaWiki Server URL (Lua) Source: https://www.mediawiki.org/wiki/Extension:Scribunto/Lua_reference_manual Retrieves the value of the `$wgServer` configuration variable, which is the base URL for the MediaWiki installation. ```Lua mw.site.server ``` -------------------------------- ### Lua Metatable: __call Example Source: https://www.mediawiki.org/wiki/Extension:Scribunto/Lua_reference_manual Shows the __call metamethod, which enables a table to be called as a function. The metamethod must be a function itself. ```lua -- Example of __call metamethod local myFuncTable = {} local meta = { __call = function(tbl, ...) print("Table was called as a function with arguments:", ...) return "called!" end } setmetatable(myFuncTable, meta) print(myFuncTable("arg1", "arg2")) -- Will call the __call function -- Output: Table was called as a function with arguments: arg1 arg2 -- called! ``` -------------------------------- ### Lua Metatable: __index Example Source: https://www.mediawiki.org/wiki/Extension:Scribunto/Lua_reference_manual Demonstrates the __index metamethod, used when a table access `t[key]` returns nil. It can either repeat the access in a specified table or call a function. ```lua -- Example of __index metamethod local myTable = {} local meta = { __index = function(tbl, key) print(string.format("Accessing key '%s' not found in table.", key)) return "default_value" end } setmetatable(myTable, meta) print(myTable.nonexistentKey) -- Will call the __index function -- Output: Accessing key 'nonexistentKey' not found in table. -- default_value ``` -------------------------------- ### Lua Metatable: __mode Example (Weak References) Source: https://www.mediawiki.org/wiki/Extension:Scribunto/Lua_reference_manual Explains the __mode metamethod for creating tables with weak references. 'k' makes keys weak, 'v' makes values weak, allowing garbage collection if no strong references exist. ```lua -- Example of __mode metamethod for weak values local weakValuesTable = {} local meta = { __mode = "v" -- Values are weak } setmetatable(weakValuesTable, meta) local obj = { name = "Object" } weakValuesTable[obj] = "Some Data" -- If 'obj' is no longer referenced elsewhere, it might be garbage collected, -- and the entry in weakValuesTable would be removed. print(weakValuesTable[obj]) -- Might print nil if obj was garbage collected ``` ```lua -- Example of __mode metamethod for weak keys local weakKeysTable = {} local meta = { __mode = "k" -- Keys are weak } setmetatable(weakKeysTable, meta) local keyObj = { id = 1 } weakKeysTable[keyObj] = "Data for Key" -- If 'keyObj' is no longer referenced elsewhere, it might be garbage collected, -- and the entry in weakKeysTable would be removed. print(weakKeysTable[keyObj]) -- Might print nil if keyObj was garbage collected ``` -------------------------------- ### Get Current MediaWiki Version (Lua) Source: https://www.mediawiki.org/wiki/Extension:Scribunto/Lua_reference_manual Provides the current version of the MediaWiki software as a string. ```Lua mw.site.currentVersion ``` -------------------------------- ### Get MediaWiki Script Path (Lua) Source: https://www.mediawiki.org/wiki/Extension:Scribunto/Lua_reference_manual Retrieves the value of the `$wgScriptPath` configuration variable, which specifies the path to MediaWiki's entry point scripts. ```Lua mw.site.scriptPath ``` -------------------------------- ### Lua Closures and Lexical Scoping Example Source: https://www.mediawiki.org/wiki/Extension:Scribunto/Lua_reference_manual Demonstrates the creation of a closure in Lua, where an inner function retains access to variables from its outer scope. ```lua -- This returns a function that adds a number to its argument function makeAdder( n ) return function( x ) -- The variable n from the outer scope is available here to be added to x return x + n end end local add5 = makeAdder( 5 ) local result = add5( 6 ) -- result will be 11 ``` -------------------------------- ### Lua Debug: traceback Function Source: https://www.mediawiki.org/wiki/Extension:Scribunto/Lua_reference_manual Generates a string containing a traceback of the current call stack. It can optionally prepend a message and start the traceback from a specified level. Returns the traceback string. ```lua debug.traceback( message, level ) ``` -------------------------------- ### Get Argument using frame:getArgument Source: https://www.mediawiki.org/wiki/Extension:Scribunto/Lua_reference_manual Retrieves an argument from the frame, returning nil if not provided. The returned object has an expand() method to get the expanded wikitext. ```lua frame:getArgument( arg ) ``` ```lua frame:getArgument{ name = arg } ``` -------------------------------- ### Raw Table Get with rawget Source: https://www.mediawiki.org/wiki/Extension:Scribunto/Lua_reference_manual Retrieves a value from a table using a key, ignoring any `__index` metamethod. This directly accesses the table's internal storage. ```lua local value = rawget(myTable, "myKey") ``` -------------------------------- ### Get Language Fallbacks Source: https://www.mediawiki.org/wiki/Extension:Scribunto/Lua_reference_manual Returns a list of fallback language codes for a given language code as determined by MediaWiki. ```Lua mw.language.getFallbacksFor( code ) ``` -------------------------------- ### Get MediaWiki Site Name (Lua) Source: https://www.mediawiki.org/wiki/Extension:Scribunto/Lua_reference_manual Retrieves the value of the `$wgSitename` configuration variable, which is the name of the wiki site. ```Lua mw.site.siteName ``` -------------------------------- ### Generating URLs and Encoding Titles in Lua Source: https://www.mediawiki.org/wiki/Extension:Scribunto/Lua_reference_manual Explains how to get the URL-encoded version of a title's text using the `partialUrl` method. ```lua local title = mw.title.new('Special:RecentChanges') print('Partial URL:', title:partialUrl()) -- Returns 'Special:RecentChanges' ``` -------------------------------- ### Lua Metatable: __newindex Example Source: https://www.mediawiki.org/wiki/Extension:Scribunto/Lua_reference_manual Illustrates the __newindex metamethod, invoked when assigning a value to a table key that doesn't exist. It can redirect the assignment to another table or execute a function. ```lua -- Example of __newindex metamethod local myTable = {} local meta = { __newindex = function(tbl, key, value) print(string.format("Attempted to set key '%s' to '%s' which does not exist.", key, value)) rawset(tbl, key, value) -- Actually set the value end } setmetatable(myTable, meta) myTable.newKey = "newValue" -- Will call the __newindex function -- Output: Attempted to set key 'newKey' to 'newValue' which does not exist. print(myTable.newKey) -- Should print the value set by __newindex -- Output: newValue ``` -------------------------------- ### Get Page Data with mw.ext.data Source: https://www.mediawiki.org/wiki/Extension:Scribunto/Lua_reference_manual Retrieves localizable tabular and map data for a given page name using the JsonConfig functionality. This is supported in the 'Data:' namespace. ```lua mw.ext.data.get( _pagename_ ) ``` -------------------------------- ### Get MediaWiki Style Path (Lua) Source: https://www.mediawiki.org/wiki/Extension:Scribunto/Lua_reference_manual Retrieves the value of the `$wgStylePath` configuration variable, which specifies the path to the site's CSS and JavaScript files. ```Lua mw.site.stylePath ``` -------------------------------- ### Getting Pages in a Specific Namespace (mw.site.stats.pagesInNamespace) Source: https://www.mediawiki.org/wiki/Extension:Scribunto/Lua_reference_manual Returns the count of pages within a specified namespace. The namespace must be identified by its numerical ID. ```Lua local namespaceId = 2 -- Example: Project namespace local pageCount = mw.site.stats.pagesInNamespace(namespaceId) print("Pages in namespace " .. namespaceId .. ": " .. pageCount) ``` -------------------------------- ### Find Pattern in UTF-8 String with mw.ustring.match Source: https://www.mediawiki.org/wiki/Extension:Scribunto/Lua_reference_manual Finds the first occurrence of a pattern within a UTF-8 string. The starting offset is character-based. ```Lua mw.ustring.match( s, pattern, init ) ``` -------------------------------- ### Lua string.match: Find pattern in string Source: https://www.mediawiki.org/wiki/Extension:Scribunto/Lua_reference_manual Searches for the first occurrence of a pattern within a string and returns captured substrings. If no captures are defined in the pattern, the entire match is returned. An optional starting position can be specified. ```lua string.match( s, pattern, init ) ``` -------------------------------- ### Scribunto Pattern Anchors Source: https://www.mediawiki.org/wiki/Extension:Scribunto/Lua_reference_manual Explains the use of '^' and '$' characters at the beginning or end of a pattern in Scribunto to anchor the match to the start or end of the subject string, respectively. ```Scribunto `^` at the beginning of a pattern anchors the match at the beginning of the subject string. `$` 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. ``` -------------------------------- ### Get Message Wikitext (Lua) Source: https://www.mediawiki.org/wiki/Extension:Scribunto/Lua_reference_manual Substitutes parameters into the message and returns the raw wikitext. Template calls and parser functions within the message remain intact. ```Lua msg:plain() ``` -------------------------------- ### Retrieving Protection Levels and Categories in Lua Source: https://www.mediawiki.org/wiki/Extension:Scribunto/Lua_reference_manual Shows how to access the `protectionLevels` and `cascadingProtection` properties to get information about a page's protection status. Also demonstrates retrieving the list of categories associated with a page using the `categories` property. ```lua local title = mw.title.makeTitle(0, 'ProtectedPage') local protection = title.protectionLevels if protection and protection.edit then print('Edit protection level:', protection.edit[1]) end local cascade = title.cascadingProtection if cascade and cascade.restrictions and cascade.restrictions.edit then print('Cascading edit protection level:', cascade.restrictions.edit[1]) end local categories = title.categories if categories then print('Categories:') for _, cat in ipairs(categories) do print('- ' .. cat.text) end end ``` -------------------------------- ### Getting Users in a Specific Group (mw.site.stats.usersInGroup) Source: https://www.mediawiki.org/wiki/Extension:Scribunto/Lua_reference_manual Returns the number of users belonging to a particular user group. The group name should be provided as a string. ```Lua local groupName = "sysop" -- Example: sysop group local userCount = mw.site.stats.usersInGroup(groupName) print("Users in group '" .. groupName .. "': " .. userCount) ``` -------------------------------- ### Lua Comment Syntax Source: https://www.mediawiki.org/wiki/Extension:Scribunto/Lua_reference_manual Illustrates the various ways to write comments in Lua, as used by Scribunto. This includes single-line comments starting with '--' and multi-line comments enclosed in double square brackets. It also shows how nested comments with varying bracket lengths are handled. ```lua -- A comment in Lua starts with a double-hyphen and runs to the end of the line. --[[ Multi-line strings & comments are adorned with double square brackets. ]] --[=[ Comments like this can have other --[[comments]] nested. ]=] --[==[ Comments like this can have other --[===[ long --[=[comments]=] --nested ]===] multiple times, even if all of them are --[[ not delimited with matching long brackets! ]===] ]==] ``` -------------------------------- ### Lua assert Function Usage Source: https://www.mediawiki.org/wiki/Extension:Scribunto/Lua_reference_manual Shows how to use the `assert` function in Lua to check for errors. If the condition is false or nil, it raises an error with a specified message. The example demonstrates a common idiom for error checking function calls. ```lua -- This doesn't check for errors local result1, result2, etc = func( ... ) -- This works the same, but does check for errors local result1, result2, etc = assert( func( ... ) ) ``` -------------------------------- ### Lua: unpack Function Source: https://www.mediawiki.org/wiki/Extension:Scribunto/Lua_reference_manual Extracts values from a table, similar to manual indexing. Defaults to starting at index 1 and ending at the table's length (#table). Handles sparse tables by returning nil for missing keys. Returns the extracted values. ```lua unpack( table, i, j ) ``` -------------------------------- ### Lua Table Creation and Population Source: https://www.mediawiki.org/wiki/Extension:Scribunto/Lua_reference_manual Demonstrates various ways to create and populate Lua tables, including direct assignment, dot notation, and array-style indexing. It also shows how different data types can be used as keys. ```lua -- Create table t = {} t["foo"] = "foo" t.bar = "bar" t[1] = "one" t[2] = "two" t[3] = "three" t[12] = "the number twelve" t["12"] = "the string twelve" t[true] = "true" t[tonumber] = "yes, even functions may be table keys" t[t] = "yes, a table may be a table key too. Even in itself." -- This creates a table roughly equivalent to the above t2 = { ["foo"] = "foo", bar = "bar", "one", "two", [12] = "the number twelve", ["12"] = "the string twelve", "three", [true] = "true", [tonumber] = "yes, even functions may be table keys", } t2[t2] = "yes, a table may be a table key too. Even in itself." ``` -------------------------------- ### Get Default Language Object (Lua) Source: https://www.mediawiki.org/wiki/Extension:Scribunto/Lua_reference_manual Retrieves a Language object representing the default language of the MediaWiki installation. This is used for various language-specific operations. ```Lua mw.message.getDefaultLanguage() ``` -------------------------------- ### Lua Basic Function Call Syntax Source: https://www.mediawiki.org/wiki/Extension:Scribunto/Lua_reference_manual Demonstrates the standard syntax for calling a Lua function with arguments, including how multiple return values are handled. ```lua func( _expression-list_ ) ``` -------------------------------- ### Working with Related Titles in Lua Source: https://www.mediawiki.org/wiki/Extension:Scribunto/Lua_reference_manual Shows how to obtain related title objects, such as the subject page title, talk page title, base page title, and root page title. It also demonstrates how to get the redirect target if the page is a redirect. ```lua local title = mw.title.new('Help:Example') local subjectTitle = title.subjectPageTitle if subjectTitle then print('Subject Page Title:', subjectTitle.text) end local talkTitle = title.talkPageTitle if talkTitle then print('Talk Page Title:', talkTitle.text) end local baseTitle = title.basePageTitle if baseTitle then print('Base Page Title:', baseTitle.text) end local rootTitle = title.rootPageTitle if rootTitle then print('Root Page Title:', rootTitle.text) end local redirectTarget = title.redirectTarget if redirectTarget then print('Redirect Target:', redirectTarget.text) end ``` -------------------------------- ### Create a basic Lua module for MediaWiki Source: https://www.mediawiki.org/wiki/Extension:Scribunto/Lua_reference_manual This code snippet demonstrates the basic structure of a Lua module for MediaWiki's Scribunto extension. It defines a module that exports a 'hello' function, which returns a simple string. This is the standard way to create callable functions within a MediaWiki Lua module. ```lua local p = {} function p.hello( frame ) return "Hello, world!" end return p ``` -------------------------------- ### Lua while loop with pseudocode equivalent Source: https://www.mediawiki.org/wiki/Extension:Scribunto/Lua_reference_manual Demonstrates the 'while' loop structure in Lua, which repeatedly executes a block of code as long as a given condition remains true. This includes the basic syntax and an explanation of its execution flow. ```Lua while _exp_ do _block_ end ``` -------------------------------- ### Get Wikibase Entity with mw.ext.UnlinkedWikibase Source: https://www.mediawiki.org/wiki/Extension:Scribunto/Lua_reference_manual Retrieves a Wikibase entity by its ID. This function is part of the UnlinkedWikibase extension. ```lua mw.ext.UnlinkedWikibase.getEntity( _id_ ) ``` -------------------------------- ### Calling parser functions with frame:callParserFunction Source: https://www.mediawiki.org/wiki/Extension:Scribunto/Lua_reference_manual Illustrates how to call MediaWiki parser functions from a Lua module using `frame:callParserFunction`. It covers different ways to pass arguments (table, varargs) and provides examples for common functions like 'ns' and '#tag'. It also highlights the need to provide empty unnamed parameters if required by the parser function. ```Lua -- Example: {{ns:0}} local ns0 = frame:callParserFunction( 'ns', { 0 } ) -- or local ns0_alt = frame:callParserFunction( 'ns', 0 ) -- or using named arguments local ns0_named = frame:callParserFunction{ name = 'ns', args = { 0 } } -- Example: {{#tag:nowiki|some text}} local nowiki_output = frame:callParserFunction( '#tag', { 'nowiki', 'some text' } ) -- or local nowiki_output_alt = frame:callParserFunction( '#tag:nowiki', 'some text' ) -- Example with named arguments in parser function: {{#tag:ref|some text|name=foo|group=bar}} local ref_output = frame:callParserFunction( '#tag', { 'ref', 'some text', name = 'foo', group = 'bar' } ) -- Example requiring an empty unnamed parameter: -- frame:callParserFunction( '#someparserfunction', { '', name = 'foo', group = 'bar' } ) ``` -------------------------------- ### Get Language Code from Object Source: https://www.mediawiki.org/wiki/Extension:Scribunto/Lua_reference_manual Retrieves the language code string associated with a given language object. ```Lua lang:getCode() ``` -------------------------------- ### Lua Variable Arguments Syntax Source: https://www.mediawiki.org/wiki/Extension:Scribunto/Lua_reference_manual Shows how to declare functions that accept a variable number of arguments using the `...` notation and how to access them. ```lua function _name_optional ( _var-list_, ... ) _block_ end -- or function _name_optional ( ... ) _block_ end ``` -------------------------------- ### Scribunto Lua Test Provider with TestFramework Source: https://www.mediawiki.org/wiki/Extension:Scribunto/Lua_reference_manual Illustrates how to structure a Scribunto Lua test file using the `Module:TestFramework`. It demonstrates returning a test provider object containing test definitions. ```lua local testframework = require 'Module:TestFramework' return testframework.getTestProvider( { -- Tests go here } ) ``` -------------------------------- ### Load libraryUtil in Lua Source: https://www.mediawiki.org/wiki/Extension:Scribunto/Lua_reference_manual Loads the libraryUtil module, which provides utility functions for implementing Scribunto libraries. This is a common first step when developing custom Scribunto modules. ```lua libraryUtil = require( 'libraryUtil' ) ``` -------------------------------- ### Get Current Page Title Object (Lua) Source: https://www.mediawiki.org/wiki/Extension:Scribunto/Lua_reference_manual Retrieves and returns the title object corresponding to the current page being processed. ```Lua mw.title.getCurrentTitle() ``` -------------------------------- ### Lua Combined Method and Named Arguments Source: https://www.mediawiki.org/wiki/Extension:Scribunto/Lua_reference_manual Illustrates how method calls can be combined with the named argument syntax for more complex object-oriented operations. ```lua table:name{ arg1 = _exp_, arg2 = _exp_ } -- equivalent to table.name( table, { arg1 = _exp_, arg2 = _exp_ } ) ``` -------------------------------- ### Get Default Content Language Object Source: https://www.mediawiki.org/wiki/Extension:Scribunto/Lua_reference_manual Returns a language object representing the wiki's default content language. ```Lua mw.language.getContentLanguage() ``` ```Lua mw.getContentLanguage() ``` -------------------------------- ### Scribunto HTML Library Source: https://www.mediawiki.org/wiki/Extension:Scribunto/Lua_reference_manual Provides a fluent interface for building HTML structures from Lua. Supports creating elements, setting attributes, adding CSS, and manipulating content. ```APIDOC ## `mw.html` Library Overview Provides a fluent interface for building complex HTML from Lua. ### Functions - `mw.html.create(tagName, args)`: Creates a new mw.html object. ### Methods (on mw.html objects) - `html:attr(name, value)` or `html:attr(table)`: Sets an HTML attribute. - `html:getAttr(name)`: Gets the value of an HTML attribute. - `html:addClass(class)`: Adds a CSS class to the node. - `html:css(name, value)` or `html:css(table)`: Sets a CSS property. - `html:cssText(css)`: Adds raw CSS to the style attribute. - `html:done()`: Returns the parent node. - `html:allDone()`: Returns the root node. - `html:node(builder)`: Appends a child mw.html node. - `html:wikitext(...)`: Appends wikitext strings. - `html:newline()`: Appends a newline. - `html:tag(tagName, args)`: Appends a new child node and returns its mw.html instance. ### Example ```lua local div = mw.html.create( 'div' ) div :attr( 'id', 'testdiv' ) :css( 'width', '100%' ) :wikitext( 'Some text' ) :tag( 'hr' ) return tostring( div ) -- Output:
Some text
``` ``` -------------------------------- ### Load bit32 Library in Lua Source: https://www.mediawiki.org/wiki/Extension:Scribunto/Lua_reference_manual Demonstrates how to load the bit32 library, which emulates Lua 5.2's bitwise operations. This library operates on unsigned 32-bit integers. ```lua bit32 = require( 'bit32' ) ``` -------------------------------- ### Extract Substring from UTF-8 String with mw.ustring.sub Source: https://www.mediawiki.org/wiki/Extension:Scribunto/Lua_reference_manual Extracts a portion of a UTF-8 string using character-based start and end offsets. ```Lua mw.ustring.sub( s, i, j ) ``` -------------------------------- ### Lua Number Formatting Examples Source: https://www.mediawiki.org/wiki/Extension:Scribunto/Lua_reference_manual Demonstrates various ways to specify number constants in Lua, including decimal, scientific notation, and hexadecimal formats. Lua uses a period as the decimal separator and does not use grouping separators. Scientific notation can use 'e' or 'E'. ```Lua 123456.78 1.23e-10 123.45e20 1.23E+5 0x3A ``` -------------------------------- ### Lua Method Call Syntax (Object-Oriented) Source: https://www.mediawiki.org/wiki/Extension:Scribunto/Lua_reference_manual Explains the syntactic sugar for calling methods on Lua tables, which is equivalent to a standard function call with the table passed as the first argument. ```lua table:name( _expression-list_ ) -- equivalent to table.name( table, _expression-list_ ) ``` -------------------------------- ### Lua Local Variable Declaration Source: https://www.mediawiki.org/wiki/Extension:Scribunto/Lua_reference_manual Shows how to declare local variables in Lua, with and without initial assignment. Explains scope and initialization to nil. ```lua local myVar1 local myVar2 = "initial value" ``` -------------------------------- ### Lua string.len: Get string length Source: https://www.mediawiki.org/wiki/Extension:Scribunto/Lua_reference_manual Returns the length of a string in bytes. This function is not affected by null characters and is equivalent to the `#s` operator. ```lua string.len( s ) ``` -------------------------------- ### Load ustring library in Lua Source: https://www.mediawiki.org/wiki/Extension:Scribunto/Lua_reference_manual Loads the pure-Lua backend for the Ustring library. It is recommended to use mw.ustring instead for better performance. ```lua ustring = require( 'ustring' ) ``` -------------------------------- ### Get Slot Content with mw.slots Source: https://www.mediawiki.org/wiki/Extension:Scribunto/Lua_reference_manual Retrieves the content of a specific MCR slot for a given page name. This function is part of the WSSlots functionality. ```lua mw.slots.slotContent(_slotName_, _pageName_) ``` -------------------------------- ### Accessing Namespace Data (mw.site.namespaces) Source: https://www.mediawiki.org/wiki/Extension:Scribunto/Lua_reference_manual Demonstrates how to access information about all namespaces on the wiki using mw.site.namespaces. Data includes namespace ID, name, and properties like subpage support and content model. ```Lua local namespaces = mw.site.namespaces -- Access information for namespace 0 (Main) local mainNamespace = namespaces[0] print(mainNamespace.name) -- Output: "" print(mainNamespace.displayName) -- Output: "Main page" -- Access information for the Project namespace by name local projectNamespace = namespaces.Project print(projectNamespace.id) -- Output: 4 (example) -- Check if a namespace has subpages enabled if namespaces[2].hasSubpages then print("The Project namespace has subpages enabled.") end ``` -------------------------------- ### Load luabit modules in Lua Source: https://www.mediawiki.org/wiki/Extension:Scribunto/Lua_reference_manual Loads the 'bit' and 'hex' modules from the luabit library. These modules provide bitwise and hexadecimal operations, respectively. ```lua bit = require( 'luabit.bit' ) hex = require( 'luabit.hex' ) ``` -------------------------------- ### Get Text Directionality (LTR/RTL) Source: https://www.mediawiki.org/wiki/Extension:Scribunto/Lua_reference_manual Returns a string indicating the text directionality of the current language, either 'ltr' (left-to-right) or 'rtl' (right-to-left). ```Lua lang:getDir() ``` -------------------------------- ### Get Frame Title using frame:getTitle Source: https://www.mediawiki.org/wiki/Extension:Scribunto/Lua_reference_manual Returns the title associated with the current frame. For an invoked module, this is the module's title. ```lua frame:getTitle() ``` -------------------------------- ### List Hashing Algorithms using mw.hash.listAlgorithms Source: https://www.mediawiki.org/wiki/Extension:Scribunto/Lua_reference_manual Returns a list of supported hashing algorithms that can be used with mw.hash.hashValue(). This is a direct passthrough to the Lua hash_algos() function. ```lua mw.hash.listAlgorithms() ``` -------------------------------- ### Get Slot Data with mw.slots Source: https://www.mediawiki.org/wiki/Extension:Scribunto/Lua_reference_manual Retrieves the data associated with a specific MCR slot for a given page name. This function is part of the WSSlots functionality. ```lua mw.slots.slotData(_slotName_, _pageName_) ``` -------------------------------- ### Get Slot Model with mw.slots Source: https://www.mediawiki.org/wiki/Extension:Scribunto/Lua_reference_manual Retrieves the content model of a specific MCR slot for a given page name. This function is part of the WSSlots functionality. ```lua mw.slots.slotContentModel(_slotName_, _pageName_) ``` -------------------------------- ### Lua Function Declaration Statements Source: https://www.mediawiki.org/wiki/Extension:Scribunto/Lua_reference_manual Demonstrates equivalent ways to declare functions in Lua, including basic functions, local functions, functions as table fields, and methods. ```lua -- Basic declaration function func( _var-list_ ) _block_ end func = function ( _var-list_ ) _block_ end ``` ```lua -- Local function local function func( _var-list_ ) _block_ end local func; func = function ( _var-list_ ) _block_ end ``` ```lua -- Function as a field in a table function table.func( _var-list_ ) _block_ end table.func = function ( _var-list_ ) _block_ end ``` ```lua -- Function as a method in a table function table:func( _var-list_ ) _block_ end table.func = function ( self, _var-list_ ) _block_ end ``` -------------------------------- ### Create Module Redirect in Lua Source: https://www.mediawiki.org/wiki/Extension:Scribunto/Lua_reference_manual This code snippet demonstrates the Lua syntax recognized by MediaWiki (version 1.42+) for creating module redirects. It uses the `require` function with a module name specified in square brackets. The `[[Module:Foo]]` part should be replaced with the actual module name to redirect to. Other syntax variations are not recognized as redirects. ```lua return require [[Module:Foo]] ``` -------------------------------- ### Select Arguments with select Source: https://www.mediawiki.org/wiki/Extension:Scribunto/Lua_reference_manual Returns a specified range of arguments passed with the `...` syntax. If the index is '#', it returns the count of arguments. Handles nil values correctly within the argument list. ```lua local secondArg = select(2, ...) local argCount = select("#", ...) ``` ```lua function select( index, ... ) local t = { ... } local maxindex = table.maxn( t ) if index == "#" then return maxindex else return unpack( t, index, maxindex ) end end ``` -------------------------------- ### Log Object with Optional Prefix Source: https://www.mediawiki.org/wiki/Extension:Scribunto/Lua_reference_manual Calls mw.dumpObject and appends the result to the log buffer. An optional prefix can be prepended to the logged string. ```Lua mw.logObject( object, prefix ) ``` ```Lua mw.logObject( object ) ``` -------------------------------- ### Get Parent Frame using frame:getParent Source: https://www.mediawiki.org/wiki/Extension:Scribunto/Lua_reference_manual Retrieves the parent frame object. Useful for accessing arguments or context from the calling template or module. ```lua frame:getParent() ``` -------------------------------- ### Create Title Object with Namespace and Fragment (Lua) Source: https://www.mediawiki.org/wiki/Extension:Scribunto/Lua_reference_manual Constructs a title object specifying the namespace, title text, and optionally a fragment and interwiki prefix. Unlike mw.title.new, this function always applies the given namespace. Interwiki functionality is limited. ```Lua mw.title.makeTitle( namespace, title, fragment, interwiki ) ``` -------------------------------- ### Get Length of UTF-8 String in Codepoints with mw.ustring.len Source: https://www.mediawiki.org/wiki/Extension:Scribunto/Lua_reference_manual Calculates the length of a string based on the number of Unicode codepoints. Returns nil for invalid UTF-8 strings. ```Lua mw.ustring.len( string ) ``` -------------------------------- ### Create Title Object from ID or Text (Lua) Source: https://www.mediawiki.org/wiki/Extension:Scribunto/Lua_reference_manual Creates a title object. It can be initialized either by a page ID (which increments expensive function count if the title is new) or by a text string and an optional namespace. Invalid inputs return nil. ```Lua mw.title.new( ID ) mw.title.new( text, namespace ) ``` -------------------------------- ### Get Fallback Languages from Object Source: https://www.mediawiki.org/wiki/Extension:Scribunto/Lua_reference_manual Retrieves MediaWiki's fallback language codes for the language object. This is equivalent to calling mw.language.getFallbacksFor() with the object's code. ```Lua lang:getFallbackLanguages() ``` -------------------------------- ### Lua Named Arguments and String Literal Syntax Source: https://www.mediawiki.org/wiki/Extension:Scribunto/Lua_reference_manual Shows Scribunto's syntactic sugar for passing named arguments using a table and for passing a single string literal directly. ```lua func{ arg1 = _exp_, arg2 = _exp_ } -- equivalent to func( { arg1 = _exp_, arg2 = _exp_ } ) func"string" -- equivalent to func( "string" ) ``` -------------------------------- ### Lua Function Declaration Syntax Source: https://www.mediawiki.org/wiki/Extension:Scribunto/Lua_reference_manual Provides the basic syntax for declaring a Lua function, including optional variable lists and the function body. ```lua function _name_optional ( _var-list_optional ) _block_ end ``` -------------------------------- ### Lua: mw.allToString function Source: https://www.mediawiki.org/wiki/Extension:Scribunto/Lua_reference_manual Converts all provided arguments to strings using tostring() and concatenates them, separated by tabs. ```lua local result = mw.allToString( "hello", 123, { key = "value" } ) -- result will be "hello\t123\ttable: 0x..." ``` -------------------------------- ### Get Metatable with getmetatable Source: https://www.mediawiki.org/wiki/Extension:Scribunto/Lua_reference_manual Returns the metatable associated with a given table. For any other type, it returns nil. If the metatable contains a `__metatable` field, that value is returned instead. ```lua local mt = getmetatable(myTable) ``` -------------------------------- ### Lua Variable Swapping Assignment Source: https://www.mediawiki.org/wiki/Extension:Scribunto/Lua_reference_manual Illustrates swapping the values of two variables using simultaneous assignment in Lua. ```lua a, b = b, a ``` -------------------------------- ### Deprecated: Get Slot Templates with mw.slots Source: https://www.mediawiki.org/wiki/Extension:Scribunto/Lua_reference_manual Retrieves the templates associated with a specific MCR slot for a given page name. This function is deprecated and part of the WSSlots functionality. ```lua mw.slots.slotTemplates(_slotName_, _pageName_) ``` -------------------------------- ### Get Directionality Mark Entities (‎/‏) Source: https://www.mediawiki.org/wiki/Extension:Scribunto/Lua_reference_manual Returns HTML entities (‎ or ‏) corresponding to text directionality marks. The `opposite` parameter determines which entity is returned. ```Lua lang:getDirMarkEntity() lang:getDirMarkEntity( true ) ``` -------------------------------- ### Access Function Environment with getfenv Source: https://www.mediawiki.org/wiki/Extension:Scribunto/Lua_reference_manual Retrieves the environment (global variable table) of a function in the call stack. Availability depends on the `allowEnvFuncs` configuration. Protected environments return nil. ```lua local env = getfenv(1) -- Get the environment of the calling function ``` -------------------------------- ### Create Language Object Source: https://www.mediawiki.org/wiki/Extension:Scribunto/Lua_reference_manual Instantiates a new language object for a specified language code. Note the limit of 200 distinct language codes per page. ```Lua mw.language.new( code ) ``` ```Lua mw.getLanguage( code ) ``` -------------------------------- ### Get Directionality Marks (LRM/RLM) Source: https://www.mediawiki.org/wiki/Extension:Scribunto/Lua_reference_manual Returns a Unicode character (U+200E or U+200F) for text directionality marks. The `opposite` parameter influences whether the LTR or RTL mark is returned. ```Lua lang:getDirMark() lang:getDirMark( true ) ``` -------------------------------- ### Create Message from Fallback Sequence (Lua) Source: https://www.mediawiki.org/wiki/Extension:Scribunto/Lua_reference_manual Creates a new message object using a sequence of message keys. The first message key in the sequence that exists will be used. This is useful for providing fallback messages. ```Lua mw.message.newFallbackSequence( ... ) ``` -------------------------------- ### Lua string.sub: Extract substring Source: https://www.mediawiki.org/wiki/Extension:Scribunto/Lua_reference_manual Returns a substring of `s` starting from index `i` and ending at index `j`. Negative indices count from the end of the string. If `j` is omitted, it extracts to the end. ```lua string.sub( s, i, j ) ``` -------------------------------- ### Preprocess Wikitext using frame:preprocess Source: https://www.mediawiki.org/wiki/Extension:Scribunto/Lua_reference_manual Expands wikitext within the current frame's context, processing templates, parser functions, and parameters. Handles special tags by replacing them with strip markers. ```lua frame:preprocess( string ) ``` ```lua frame:preprocess{ text = string } ``` -------------------------------- ### Create Batch of Title Objects for Lookup (Lua) Source: https://www.mediawiki.org/wiki/Extension:Scribunto/Lua_reference_manual Creates a batch lookup object for multiple page titles. It supports looking up existence, content model, ID, and redirect status. This method can be expensive, incrementing the count for every 25 lookups. ```Lua mw.title.newBatch{ firstPage, secondPage, thirdPage } mw.title.newBatch( { firstPage, secondPage, thirdPage }, defaultNamespace ) -- Example usage: mw.title.newBatch{ "First page", "User:Bob", "Second page" }:lookupExistence():getTitles() ``` -------------------------------- ### Create and Manipulate HTML Elements with mw.html (Lua) Source: https://www.mediawiki.org/wiki/Extension:Scribunto/Lua_reference_manual Demonstrates using the mw.html library to create a div element, set its attributes and styles, append a horizontal rule, and convert the structure to a string. This is a fluent interface for HTML generation in Lua. ```Lua local div = mw.html.create( 'div' ) div :attr( 'id', 'testdiv' ) :css( 'width', '100%' ) :wikitext( 'Some text' ) :tag( 'hr' ) return tostring( div ) -- Output:
Some text
``` -------------------------------- ### bit32.extract: Extract bits from an integer Source: https://www.mediawiki.org/wiki/Extension:Scribunto/Lua_reference_manual Extracts a specified number of bits (width) from an integer (n), starting from a given bit position (field). Bits are numbered from 0 (least-significant) to 31 (most-significant). ```lua bit32.extract( n, field, width ) ``` -------------------------------- ### Format List to Prose with mw.text.listToText Source: https://www.mediawiki.org/wiki/Extension:Scribunto/Lua_reference_manual Joins a list of items into a human-readable string using specified separators and conjunctions. ```Lua -- 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 ' ) ``` -------------------------------- ### Protected Function Call with pcall Source: https://www.mediawiki.org/wiki/Extension:Scribunto/Lua_reference_manual Calls a function in protected mode, catching errors. Returns `true` and the function's return values on success, or `false` and an error message on failure. Useful for handling potential runtime errors. ```lua local success, result = pcall(myFunction, arg1, arg2) if not success then print("Error occurred:", result) end ``` ```lua function pcall( f, ... ) try return true, f( ... ) catch ( message ) return false, message end end ``` -------------------------------- ### Lua Math: fmod Function Source: https://www.mediawiki.org/wiki/Extension:Scribunto/Lua_reference_manual Calculates the floating-point remainder of the division of x by y. The quotient is rounded towards zero. For example, math.fmod(10, 3) yields 1. Returns the remainder of x / y. ```lua math.fmod( x, y ) ``` -------------------------------- ### Compare Two Titles (Lua) Source: https://www.mediawiki.org/wiki/Extension:Scribunto/Lua_reference_manual Compares two titles and returns -1, 0, or 1 to indicate if the first title is less than, equal to, or greater than the second. The comparison considers interwiki prefix, namespace number, and the unprefixed title text. ```Lua mw.title.compare( a, b ) ``` -------------------------------- ### Load Data Module Source: https://www.mediawiki.org/wiki/Extension:Scribunto/Lua_reference_manual Loads data from a specified Lua module. The module is evaluated only once per page. The returned value must be a table containing only basic types (booleans, numbers, strings, tables) and no metatables. Provides read-only access to the loaded data. ```Lua local data = mw.loadData( 'Module:Convert/data' ) ``` -------------------------------- ### Get Unicode Arrow Character Source: https://www.mediawiki.org/wiki/Extension:Scribunto/Lua_reference_manual Returns a Unicode arrow character based on the specified direction ('forwards', 'backwards', 'left', 'right', 'up', 'down'). The appearance of 'forwards' and 'backwards' arrows depends on the language's text directionality. ```Lua lang:getArrow( 'right' ) lang:getArrow( 'forwards' ) ``` -------------------------------- ### Create Template Parser Value using frame:newTemplateParserValue Source: https://www.mediawiki.org/wiki/Extension:Scribunto/Lua_reference_manual Returns an object with an expand() method that expands a template with given arguments. This is an efficient way to handle template expansions. ```lua frame:newTemplateParserValue{ title = title, args = table } ``` -------------------------------- ### Lua Varargs Manipulation with `select()` Source: https://www.mediawiki.org/wiki/Extension:Scribunto/Lua_reference_manual Demonstrates using the `select()` function to handle variable arguments, specifically for counting and concatenating them. ```lua local join = function ( separator, ... ) -- get the extra arguments as a new table local args = { ... } -- get the count of extra arguments, correctly local n = select( '#', ... ) return table.concat( args, separator, 1, n ) end local result = join( ', ', 'foo', 'bar', 'baz' ) -- returns the string "foo, bar, baz" ``` -------------------------------- ### Iterate Table with ipairs Source: https://www.mediawiki.org/wiki/Extension:Scribunto/Lua_reference_manual Provides an iterator for numerically indexed sequential table elements (1, 2, 3, ...). It returns an iterator function, the table, and an initial index of 0. The iteration stops when an element is nil. Can be overridden by an `__ipairs` metamethod. ```lua for i, v in ipairs(myTable) do print(i, v) end ``` -------------------------------- ### Iterate Table with pairs Source: https://www.mediawiki.org/wiki/Extension:Scribunto/Lua_reference_manual Provides an iterator for all key-value pairs in a table, similar to `next`. It returns an iterator function, the table, and an initial key of nil. Can be overridden by a `__pairs` metamethod. ```lua for k, v in pairs(myTable) do print(k, v) end ``` -------------------------------- ### bit32.replace: Replace bits in an integer Source: https://www.mediawiki.org/wiki/Extension:Scribunto/Lua_reference_manual Replaces a specified number of bits (width) within an integer (n), starting from a given bit position (field), with the low 'width' bits from another integer (v). Accessing bits outside the 0-31 range is an error. ```lua bit32.replace( n, v, field, width ) ``` -------------------------------- ### Iterate Table Keys with next Source: https://www.mediawiki.org/wiki/Extension:Scribunto/Lua_reference_manual Allows iteration over the key-value pairs of a table. When called with nil or no key, it returns the first pair. Subsequent calls with the returned key yield the next pair. Returns nil when no more keys exist. Order is not guaranteed. ```lua local k, v = next(myTable) while k do print(k, v) k, v = next(myTable, k) end ``` ```lua if next(myTable) == nil then print("Table is empty") end ``` -------------------------------- ### Lua string.rep: Repeat string Source: https://www.mediawiki.org/wiki/Extension:Scribunto/Lua_reference_manual Returns a new string formed by concatenating the input string `s` exactly `n` times. ```lua string.rep( s, n ) ``` -------------------------------- ### Title Object URL Generation (Lua) Source: https://www.mediawiki.org/wiki/Extension:Scribunto/Lua_reference_manual Generates different types of URLs for a given title. Supports optional query parameters and protocol schemes. Query parameters can be a table or a string. ```Lua local title = mw.title.new('ExamplePage') -- Get full URL with default relative protocol local fullUrl = title.fullUrl -- Get full URL with HTTPS protocol and a query string local fullUrlHttps = title.fullUrl('action=edit') -- Get full URL with HTTPS protocol and a query table local fullUrlQueryTable = title.fullUrl({['action'] = 'edit', ['section'] = 'new'}) -- Get local URL with a query table local localUrl = title.localUrl({['action'] = 'edit'}) -- Get canonical URL local canonicalUrl = title.canonicalUrl() ``` -------------------------------- ### Lua return statement and tail calls Source: https://www.mediawiki.org/wiki/Extension:Scribunto/Lua_reference_manual Explains the 'return' statement in Lua, used for returning values from functions or chunks. It details how multiple values can be returned and describes the behavior of tail calls, where the current stack frame is reused for function calls as the last action in a block. ```Lua return _expression-list_ ``` -------------------------------- ### Create Child Frame using frame:newChild Source: https://www.mediawiki.org/wiki/Extension:Scribunto/Lua_reference_manual Creates a new Frame object as a child of the current frame, allowing for specific environments for nested calls. Intended for debugging and testing, not production emulation. ```lua frame:newChild{ title = title, args = table } ``` -------------------------------- ### Scribunto PHP Test Case Structure Source: https://www.mediawiki.org/wiki/Extension:Scribunto/Lua_reference_manual Defines a basic PHP class structure for Scribunto unit tests, extending `Scribunto_LuaEngineTestBase`. It specifies the module name and provides a method to map test module names to their file paths. ```php class ''ClassName''Test extends Scribunto_LuaEngineTestBase { protected static $moduleName = 'ClassNameTest'; function getTestModules() { return parent::getTestModules() + array( 'ClassNameTest' => __DIR__ . '/ClassNameTests.lua'; ); } } ``` -------------------------------- ### Format Duration into Human-Readable Units Source: https://www.mediawiki.org/wiki/Extension:Scribunto/Lua_reference_manual Converts a duration in seconds into a more readable string with units like hours, minutes, and seconds. Allows specifying which units to include in the output. ```Lua lang:formatDuration( 12345 ) lang:formatDuration( 12345, { 'hours', 'minutes', 'seconds' } ) ``` -------------------------------- ### Load a module in Scribunto Source: https://www.mediawiki.org/wiki/Extension:Scribunto/Lua_reference_manual Demonstrates how to load a custom Lua module named 'Module:Giving' and access its exported data. The 'require' function handles module loading and returns the module's value, which is then used to retrieve 'someDataValue'. ```lua local giving = require( "Module:Giving" ) local value = giving.someDataValue -- value is now 'Hello!' ``` -------------------------------- ### Lua generic for loop with pseudocode equivalent Source: https://www.mediawiki.org/wiki/Extension:Scribunto/Lua_reference_manual Describes the generic 'for' loop in Lua, which iterates using iterator functions. It provides pseudocode to illustrate how iterator functions, static variables, and loop variables are managed, and discusses efficiency considerations for iterator implementation. ```Lua for _var-list_ in _expression-list_ do _block_ end ``` ```Pseudocode do local func, static, var = expression-list while true do local var-list = func( static, var ) var = var1 -- ''var1'' is the first variable in ''var-list'' if var == nil then break end block end end ```