Toggle menu
15
236
70
27.6K
Kenshi Wiki
Toggle preferences menu
Toggle personal menu
Not logged in
Your IP address will be publicly visible if you make any edits.

Help:Lua: Difference between revisions

Wikipedia information page
Created page with "{{WikiProject Lua header}} == "Hello world" == * See Module:Example ==Documentation== * Scribunto Lua reference manual (Manual for the Mediawiki implementation) * [http://www.lua.org/pil/contents.html#P1 Programming in Lua] (Official book/introduction to Lua) * [http://lua-users.org/wiki/TutorialDirectory Lua tutorials at lua-users.org] * Wiktionary:Lua on English Wiktionary: contains not..."
 
No edit summary
 
Line 1: Line 1:
{{short description|Wikipedia project page for MediaWiki Lua modules}}
{{WikiProject Lua header}}
{{WikiProject Lua header}}
{{Information page|WP:LUA|WP:MODULE}}
{{Namespaces}}


== "Hello world" ==
[[Lua (programming language)|Lua]] is a programming language available through the [[mw:Extension:Scribunto|Scribunto]] [[MediaWiki extension]] on the English Wikipedia. Since February 2013, Lua code can be embedded into wiki templates by using the "<nowiki>{{#invoke:}}</nowiki>" functionality of Scribunto. This extension supports Lua 5.1 {{as of|lc=y|2022|10}}.
* See [[Module:Example]]


==Documentation==
Lua [[source code]] is stored in pages called modules (e.g., the source code for a module named "Example" would be at [[Module:Example]]). Individual modules are then invoked, by code <code><nowiki>{{#invoke:<Module name>|<Function name>|(optional) param1 | param2...}}</nowiki></code>, for example:
* [[mw:Extension:Scribunto/Lua reference manual|Scribunto Lua reference manual]] (Manual for the Mediawiki implementation)
{| class="wikitable"
* [http://www.lua.org/pil/contents.html#P1 Programming in Lua] (Official book/introduction to Lua)
|-
* [http://lua-users.org/wiki/TutorialDirectory Lua tutorials at lua-users.org]
! Wikitext
* [[wikt:Wiktionary:Scribunto|Wiktionary:Lua]] on English Wiktionary: contains notes on efficiency and on dealing with Unicode and UTF-8
! Result
|-
|  <code><nowiki>{{#invoke:Example|hello}}</nowiki></code>
| {{#invoke:Example|hello}}
|}


==How-to guides==
== Running a module ==
* [[Help:Lua for beginners]]
Modules are run on normal wiki pages using the #invoke parser function. The syntax of #invoke is similar to template syntax, but with some differences. The most important difference is that you need to specify a ''function name''. A function is a set of instructions that takes input values, processes them, and returns an output value.<ref>You can also have multiple output values, but functions that do this are not normally meant to be accessed from wiki pages.</ref> This is much like what a template does: you give it arguments, it processes them, and you get a result. However, you can define many functions in one Lua module, whereas you can only define one template on one page.
* [[Wikipedia:Lua style guide]] &ndash; standards to improve the readability of code through consistency
* [[:File:WMF Tech Talk 2013-02-28 slides - Scribunto presentation.pdf|"What do converted templates look like?" (slideshow)]]
* [[Wikipedia:Lua string functions]]
* [[Wikipedia:Guide to Scribbling]]


==Debugging modules==
Furthermore, you can't just run a Lua module directly – you can only run one of the module's functions. The module is just a container for the functions, and doesn't do anything by itself. So there are two reasons that we need to input a function name: we can't run a module by itself, and without specifying a function name, Lua will not know which function it is we want to run.
* [[Module:SimpleDebug]] - It allows to collect and view the values of one or several variables and/or customized labels of several points of a lua program.


== Testing modules ==
The simplest way to run a module from a wiki page is like this:
* [[Module:UnitTests]] - used to power many module [[unit test]]s, which are usually found by the name "Module:(your-module-name)/tests".
* [[Module:Example/testcases]] &ndash; [[Module talk:Example/testcases|Results]] - Unit tests for [[Module:Example]] (the "hello world" module)


== Profiling modules and functions ==
&#123;{#invoke:''module name''|''function name''}}
* [[Module:Timing]] &ndash; module to do some simple probing of timing issues, mostly to spot and fix load problems


==Patterns==
For example, we can run [[Module:Example]] in this way, which has a function named "hello".
* [[:mw:Extension:Scribunto/Lua_reference_manual#Patterns]]
* <code><nowiki>{{#invoke:Example|hello}}</nowiki></code> → {{#invoke:Example|hello}}
* [[:mw:Extension:Scribunto/Lua_reference_manual#Ustring_patterns]]
* [http://lua-users.org/wiki/PatternsTutorial PatternsTutorial]
* REGEX (as applied by [[WP:AWB]]): [[WP:REGEX]]


==Wikipedia resources==
=== Using arguments ===
* [[Special:PrefixIndex/Module:Sandbox]] - allows you to work on a set of files within a sandbox prefix.
Arguments are passed to modules in the same way that they are passed to templates. Note, however, that the text after the first pipe character is always the function name; the first positional argument is the text after the ''second'' pipe.
 
&#123;{#invoke:''module name''|''function name''|''first positional argument''|''second positional argument''|''named argument'' = ''value''}}
 
In [[Module:Example]], the "hello_to" function greets different people depending on the first positional argument. It works like this:
* <code><nowiki>{{#invoke:Example|hello_to|Kate}}</nowiki></code> → {{#invoke:Example|hello_to|Kate}}
* <code><nowiki>{{#invoke:Example|hello_to|Fred}}</nowiki></code> → {{#invoke:Example|hello_to|Fred}}
 
A third function in [[Module:Example]], named "count_fruit", uses the named arguments <code>bananas</code> and <code>apples</code> to count the number of bananas and apples we have. It can be run like this:
* <code><nowiki>{{#invoke:Example|count_fruit|apples=3|bananas=4}}</nowiki></code> → {{#invoke:Example|count_fruit|apples=3|bananas=4}}
* <code><nowiki>{{#invoke:Example|count_fruit|bananas=5|apples=2}}</nowiki></code> → {{#invoke:Example|count_fruit|bananas=5|apples=2}}
 
Most modules have a documentation page explaining what arguments can be used and what their effects will be.
 
===On VisualEditor===
{{tracked|T205197|Open}}
Currently, [[WP:VisualEditor|VisualEditor]] does not allow invoking modules through its interface, even though it can edit existing module invocations. A possible workaround for this is to use {{tl|invoke}} instead. The syntax is very similar to #invoke, so, to use it on VisualEditor, its first unnamed argument must be the module's name, the second the function name, and all arguments passed to the module can be specified [[Help:VisualEditor#Template_parameters|the same way as for regular templates]]. Note that it won't work for modules that expect to read data from the calling template (as the calling template is {{tl|invoke}} itself rather than the page that uses it) as the example below demonstrates:
*{{mlx|TEMPLATENAME|main}} → {{#invoke:TEMPLATENAME|main}}
*<code><nowiki>{{invoke|TEMPLATENAME|main}}</nowiki></code> → {{invoke|TEMPLATENAME|main}}
However, that is a pathological case, most modules will behave the same either way.
 
== Request a script ==
Visit '''[[Wikipedia talk:Lua]]''' to request help in writing a Lua script to perform a specific task on Wikipedia or another Wikimedia Foundation project.
 
== History ==
{{see also|Wikipedia:Before Lua}}
[[mw:Manual:MediaWiki architecture#Magic words and templates|Sordid history]]. {{tl|qif}}, [[mw:Help:Extension:ParserFunctions|ParserFunctions]], [[mw:Extension:Lua|Lua extension]], wiki scripting language debated (JavaScript v. Lua), [[mw:Extension:WikiScripts]], Tim writes [[mw:Extension:Scribunto|Scribunto]] with initial support for Lua.
 
Discussed for years, Lua was installed in 2012 for testing on [[test2wiki:|test2.wikipedia.org]], with open invitation to all editors to experiment with developing Lua modules. Lua was installed on the English Wikipedia in February 2013, after testing on mediawiki.org and Wikimedia test wikis.
 
== About Lua ==
:''See also [[:File:WMF Tech Talk 2013-02-28 slides - Scribunto presentation.pdf|Brad Jorsch's short presentation for a basic example of how to convert a wikitext template into a Lua module.]]''
Lua is a [[scripting language]] which can be used to analyze data, calculate expressions, and format results using functions or [[object-oriented programming]]. Although some Lua scripts can be kept simple, for easy understanding, Lua allows complex structures including tables, dynamic functions, and [[associative array]]s where index [[subscript]]s can be words as well as index numbers. Lua also supports [[recursion]] of re-nested functions, so care should be taken to avoid excessive complexity where other users would not understand how to maintain a Lua module. The following is the source code of the module used for the examples above.
{{#tag:syntaxhighlight|{{#invoke:String|replace|{{#invoke:Page|getContent|Module:Example|as=raw}}|local function lucky(.-)return p|return p|plain=false}}|lang=lua|line=1}}
A sample of Lua is highlighted by tag {{tag|syntaxhighlight|attribs=lang="lua"|wrap=yes}} placed around the Lua source code. To view some more complex examples of Lua, see article: "[[Lua (programming language)]]".
 
For instructions on how to use Lua within MediaWiki (and hence Wikipedia), see [[mw:Extension:Scribunto/Lua reference manual]].
 
== Unit testing ==
{{see also|:Category:Modules for test tools}}
 
A few [[unit test]]ing frameworks are available for Lua scripts on Wikipedia. These allow an editor to execute the module with a given set of inputs and verify that the expected outputs are produced. They are useful for rapidly detecting [[software regression]]s, where modifications to a script introduce new (or identify old) problems.
 
By convention, unit tests for a module like [[Module:Example]] are placed in [[Module:Example/testcases]], and are executed on [[Module talk:Example/testcases]].
 
'''[[Module:UnitTests]]''' is the prefilled code used when creating a testcases page. You run these unit tests by placing <code><nowiki>{{#invoke:Example/testcases|run_tests}}</nowiki></code> on the testcases talk page.
 
[[Module:ScribuntoUnit]] is another widely used test framework. [[:Category:Modules for test tools]] has a few others to review which may be interesting.
 
== MediaWiki-specific features ==
Overall: Lua can only get input as text strings passed to the <code><nowiki>{{#invoke:}}</nowiki></code> and what can be fetched via mw.title.new(...):getContent() and frame:expandTemplate(). Lua output will not be preprocessed unless frame:preprocess() is explicitly called, meaning that template calls, parser functions, etc. in the output will not work correctly. Also, all Lua in the page is limited to 10 seconds CPU time (you can look in the source code of a rendered page to see how long a template or module took to parse). And relative to standard Lua, Scribunto's Lua lacks all sorts of functions (see {{section link|mw:Extension:Scribunto/Lua reference manual|Differences from standard Lua}}).
 
=== Lua input limitations ===
Lua code in Scribunto is only run when the page is being parsed. Therefore, the only user input that Lua can receive is by ''page editing'' – it cannot create a box that calculates the square root of a number you type in, or recalculate a piece of the Mandelbrot set depending on which part of the parent set you click on. The input Lua can receive includes any transcludeable text page on Wikipedia. This does ''not'' include graphics files (not even [[Wikipedia:SVG help|.SVG]] files, although they are actually text, unless you cut and paste it onto a Wiki text page), the list of pages listed in a [[Help:Category|category]], nor the contents of [[Wikipedia:Transclusion#Special pages|non-transcludeable]] [[Help:Special|special pages]].
 
=== Wikitext ===
Transcluded Wikipedia headers frequently contain a hidden code such as "UNIQ5ae8f2aa414ff233-h-3--QINU" which may need to be stripped out in order for them to be parsed effectively.
 
Wikilinks using the [[Wikipedia:Pipe trick|pipe trick]] <kbd ><nowiki>[[Wikipedia:Help| ]]</nowiki></kbd> won't work if returned as output – they need to be written explicitly as <kbd><nowiki>[[Wikipedia:Help|Help]]</nowiki></kbd>. Other pre-save transforms, such as replacing <kbd>~~<nowiki/>~~</kbd > with signatures, will also fail to be processed. Template transclusions, parser function calls, and variable substitutions (i.e. anything with a <code><nowiki>{{...}}</nowiki></code>) will not be processed, nor will tags such as {{tag|ref|o}} or {{tag|nowiki|o}}. Use [[mw:Extension:Scribunto/Lua reference manual#frame:extensionTag|<syntaxhighlight lang="lua" inline>frame:extensionTag</syntaxhighlight>]] to add tags like {{tag|ref|o}} or {{tag|syntaxhighlight|o}} to output.
 
== Labeling converted templates ==
{{lua|Module:Example}}
Please place the {{tl|lua}} template on the documentation subpage of all templates that use Lua. It will help to better communicate Lua usage and template conversions.
 
== See also ==
=== Categories ===
* [[:Category:Lua language on Wikipedia]] – usage of Lua on Wikipedia
* [[:Category:Wikipedia modules]] – top-level category for Lua modules
** [[:Category:Lua metamodules]] – modules that aid other Lua modules
* [[:Category:Lua-based templates]] – groups of Lua-based templates
* [[:Category:Wikipedia Lua-related templates]] – templates related to the usage of Lua on Wikipedia
 
=== Other pages ===
* [[Special:PrefixIndex/Module:]] – tracking of Lua modules can be done by using [[Special:PrefixIndex]]
* [[Help:Lua debugging]] – a how-to guide about [[debugging]] Lua modules
* [[Module:Sandbox]] provides a pseudo-namespace for experimenting with Lua modules
* [[mw:Manual:Coding conventions/Lua|Manual:Coding conventions/Lua]] – standards to improve the readability of code through consistency
* [[mw:Extension:Scribunto/Lua reference manual]]
* [[Wikipedia:Advanced template coding]]
 
== Notes ==
{{reflist}}


{{Wikipedia technical help|collapsed}}
{{Wikipedia technical help|collapsed}}


[[Category:Module help| ]]
[[Category:Module help| ]]
[[Category:Lua language on Wikipedia]]

Latest revision as of 00:05, 8 March 2025

Namespaces
Subject namespaces Talk namespaces
0 (Main/Article) Talk 1
2 User User talk 3
4 Kenshi Wiki Kenshi Wiki talk 5
6 File File talk 7
8 MediaWiki MediaWiki talk 9
10 Template Template talk 11
12 Help Help talk 13
14 Category Category talk 15
100 [[Wikipedia:Portal|]] 101
118 [[Wikipedia:Drafts|]] 119
126 [[Wikipedia:Manual of Style|]] 127
710 [[mw:Extension:TimedMediaHandler|]] 711
828 Module Module talk 829
Former namespaces
108 Book Book talk 109
442 Course Course talk 443
444 Institution Institution talk 445
446 Education Program Education Program talk 447
2300 Gadget Gadget talk 2301
2302 Gadget definition Gadget definition talk 2303
2600 Topic 2601
Virtual namespaces
-1 Special
-2 Media
Current list

Lua is a programming language available through the Scribunto MediaWiki extension on the English Wikipedia. Since February 2013, Lua code can be embedded into wiki templates by using the "{{#invoke:}}" functionality of Scribunto. This extension supports Lua 5.1 Template:As of.

Lua source code is stored in pages called modules (e.g., the source code for a module named "Example" would be at Module:Example). Individual modules are then invoked, by code {{#invoke:<Module name>|<Function name>|(optional) param1 | param2...}}, for example:

Wikitext Result
{{#invoke:Example|hello}} Hello World!

Running a module

Modules are run on normal wiki pages using the #invoke parser function. The syntax of #invoke is similar to template syntax, but with some differences. The most important difference is that you need to specify a function name. A function is a set of instructions that takes input values, processes them, and returns an output value.[1] This is much like what a template does: you give it arguments, it processes them, and you get a result. However, you can define many functions in one Lua module, whereas you can only define one template on one page.

Furthermore, you can't just run a Lua module directly – you can only run one of the module's functions. The module is just a container for the functions, and doesn't do anything by itself. So there are two reasons that we need to input a function name: we can't run a module by itself, and without specifying a function name, Lua will not know which function it is we want to run.

The simplest way to run a module from a wiki page is like this:

{{#invoke:module name|function name}}

For example, we can run Module:Example in this way, which has a function named "hello".

  • {{#invoke:Example|hello}} → Hello World!

Using arguments

Arguments are passed to modules in the same way that they are passed to templates. Note, however, that the text after the first pipe character is always the function name; the first positional argument is the text after the second pipe.

{{#invoke:module name|function name|first positional argument|second positional argument|named argument = value}}

In Module:Example, the "hello_to" function greets different people depending on the first positional argument. It works like this:

  • {{#invoke:Example|hello_to|Kate}} → Hello, Kate!
  • {{#invoke:Example|hello_to|Fred}} → Hello, Fred!

A third function in Module:Example, named "count_fruit", uses the named arguments bananas and apples to count the number of bananas and apples we have. It can be run like this:

  • {{#invoke:Example|count_fruit|apples=3|bananas=4}} → I have 4 bananas and 3 apples
  • {{#invoke:Example|count_fruit|bananas=5|apples=2}} → I have 5 bananas and 2 apples

Most modules have a documentation page explaining what arguments can be used and what their effects will be.

On VisualEditor

Currently, VisualEditor does not allow invoking modules through its interface, even though it can edit existing module invocations. A possible workaround for this is to use {{invoke}} instead. The syntax is very similar to #invoke, so, to use it on VisualEditor, its first unnamed argument must be the module's name, the second the function name, and all arguments passed to the module can be specified the same way as for regular templates. Note that it won't work for modules that expect to read data from the calling template (as the calling template is {{invoke}} itself rather than the page that uses it) as the example below demonstrates:

However, that is a pathological case, most modules will behave the same either way.

Request a script

Visit Wikipedia talk:Lua to request help in writing a Lua script to perform a specific task on Wikipedia or another Wikimedia Foundation project.

History

Sordid history. {{qif}}, ParserFunctions, Lua extension, wiki scripting language debated (JavaScript v. Lua), mw:Extension:WikiScripts, Tim writes Scribunto with initial support for Lua.

Discussed for years, Lua was installed in 2012 for testing on test2.wikipedia.org, with open invitation to all editors to experiment with developing Lua modules. Lua was installed on the English Wikipedia in February 2013, after testing on mediawiki.org and Wikimedia test wikis.

About Lua

See also Brad Jorsch's short presentation for a basic example of how to convert a wikitext template into a Lua module.

Lua is a scripting language which can be used to analyze data, calculate expressions, and format results using functions or object-oriented programming. Although some Lua scripts can be kept simple, for easy understanding, Lua allows complex structures including tables, dynamic functions, and associative arrays where index subscripts can be words as well as index numbers. Lua also supports recursion of re-nested functions, so care should be taken to avoid excessive complexity where other users would not understand how to maintain a Lua module. The following is the source code of the module used for the examples above.

local p = {}	    --All Lua modules on Wikipedia must begin by defining a variable 
                    --that will hold their externally accessible functions.
                    --Such variables can have whatever name you want and may 
                    --also contain various data as well as functions.
p.hello = function( frame )     --Add a function to "p".  
                                        --Such functions are callable in Wikipedia
                                        --via the #invoke command.
                                        --"frame" will contain the data that Wikipedia
                                        --sends this function when it runs. 
                                 -- 'Hello' is a name of your choice. The same name needs to be referred to when the module is used.
    
    local str = "Hello World!"  --Declare a local variable and set it equal to
                                --"Hello World!".  
    
    return str    --This tells us to quit this function and send the information in
                  --"str" back to Wikipedia.
    
end  -- end of the function "hello"
function p.hello_to(frame)		-- Add another function
	local name = frame.args[1]  -- To access arguments passed to a module, use `frame.args`
							    -- `frame.args[1]` refers to the first unnamed parameter
							    -- given to the module
	return "Hello, " .. name .. "!"  -- `..` concatenates strings. This will return a customized
									 -- greeting depending on the name given, such as "Hello, Fred!"
end
function p.count_fruit(frame)
	
	local num_bananas = tonumber(frame.args.bananas) or 0	-- Named arguments ({{#invoke:Example|count_fruit|foo=bar}})
	local num_apples = tonumber(frame.args.apples) or 0		-- are likewise accessed by indexing `frame.args` by name (`frame.args["bananas"]`,
															--  or equivalently `frame.args.bananas`.
															
	local conj_bananas = num_bananas == 1 and 'banana' or 'bananas'
    local conj_apples = num_apples == 1 and 'apple' or 'apples'
    										-- Ternary operators assign values based on a condition in a compact way.
											-- Here, `conj_bananas` gets `'banana'` if `num_bananas` is 1, else `'bananas'`.
											-- Similarly, `conj_apples` gets `'apple'` if `num_apples` is 1, else `'apples'`.
    
    return 'I have ' .. num_bananas ..  ' ' .. conj_bananas .. ' and ' .. num_apples .. ' ' .. conj_apples														
										   -- Like above, concatenate a bunch of strings together to produce
										   -- a sentence based on the arguments given.
end

return p    --All modules end by returning the variable containing their functions to Wikipedia.
-- Now we can use this module by calling {{#invoke: Example | hello }},
-- {{#invoke: Example | hello_to | foo }}, or {{#invoke:Example|count_fruit|bananas=5|apples=6}}
-- Note that the first part of the invoke is the name of the Module's wikipage,
-- and the second part is the name of one of the functions attached to the 
-- variable that you returned.

-- The "print" function is not allowed in Wikipedia.  All output is accomplished
-- via strings "returned" to Wikipedia.

A sample of Lua is highlighted by tag <syntaxhighlight lang="lua">...</syntaxhighlight> placed around the Lua source code. To view some more complex examples of Lua, see article: "Lua (programming language)".

For instructions on how to use Lua within MediaWiki (and hence Wikipedia), see mw:Extension:Scribunto/Lua reference manual.

Unit testing

A few unit testing frameworks are available for Lua scripts on Wikipedia. These allow an editor to execute the module with a given set of inputs and verify that the expected outputs are produced. They are useful for rapidly detecting software regressions, where modifications to a script introduce new (or identify old) problems.

By convention, unit tests for a module like Module:Example are placed in Module:Example/testcases, and are executed on Module talk:Example/testcases.

Module:UnitTests is the prefilled code used when creating a testcases page. You run these unit tests by placing {{#invoke:Example/testcases|run_tests}} on the testcases talk page.

Module:ScribuntoUnit is another widely used test framework. Category:Modules for test tools has a few others to review which may be interesting.

MediaWiki-specific features

Overall: Lua can only get input as text strings passed to the {{#invoke:}} and what can be fetched via mw.title.new(...):getContent() and frame:expandTemplate(). Lua output will not be preprocessed unless frame:preprocess() is explicitly called, meaning that template calls, parser functions, etc. in the output will not work correctly. Also, all Lua in the page is limited to 10 seconds CPU time (you can look in the source code of a rendered page to see how long a template or module took to parse). And relative to standard Lua, Scribunto's Lua lacks all sorts of functions (see mw:Extension:Scribunto/Lua reference manual  Differences from standard Lua).

Lua input limitations

Lua code in Scribunto is only run when the page is being parsed. Therefore, the only user input that Lua can receive is by page editing – it cannot create a box that calculates the square root of a number you type in, or recalculate a piece of the Mandelbrot set depending on which part of the parent set you click on. The input Lua can receive includes any transcludeable text page on Wikipedia. This does not include graphics files (not even .SVG files, although they are actually text, unless you cut and paste it onto a Wiki text page), the list of pages listed in a category, nor the contents of non-transcludeable special pages.

Wikitext

Transcluded Wikipedia headers frequently contain a hidden code such as "UNIQ5ae8f2aa414ff233-h-3--QINU" which may need to be stripped out in order for them to be parsed effectively.

Wikilinks using the pipe trick [[Wikipedia:Help| ]] won't work if returned as output – they need to be written explicitly as [[Wikipedia:Help|Help]]. Other pre-save transforms, such as replacing ~~~~ with signatures, will also fail to be processed. Template transclusions, parser function calls, and variable substitutions (i.e. anything with a {{...}}) will not be processed, nor will tags such as <ref> or <nowiki>. Use frame:extensionTag to add tags like <ref> or <syntaxhighlight> to output.

Labeling converted templates

Please place the {{lua}} template on the documentation subpage of all templates that use Lua. It will help to better communicate Lua usage and template conversions.

See also

Categories

Other pages

Notes

  1. You can also have multiple output values, but functions that do this are not normally meant to be accessed from wiki pages.

Template:Wikipedia technical help