Movatterモバイル変換


[0]ホーム

URL:


Jump to content
WikipediaThe Free Encyclopedia
Search

Wikipedia:Lua

Page semi-protected
From Wikipedia, the free encyclopedia
(Redirected fromWikipedia:Module)
Wikipedia project page for MediaWiki Lua modules

Lua(talk)HelpTo doResourcesReference manual
Wikipedia information page
This is aninformation page.
It is neither anencyclopedia article nor one ofWikipedia's policies or guidelines; rather, its purpose is to explain certain aspects of Wikipedia's norms, customs, technicalities, or practices. It may reflect differing levels ofconsensus andvetting.
Namespaces
Subject namespacesTalk namespaces
0(Main/Article)Talk1
2UserUser talk3
4WikipediaWikipedia talk5
6FileFile talk7
8MediaWikiMediaWiki talk9
10TemplateTemplate talk11
12HelpHelp talk13
14CategoryCategory talk15
100PortalPortal talk101
118DraftDraft talk119
126MOSMOS talk127
710TimedTextTimedText talk711
828ModuleModule talk829
1728EventEvent talk1729
Former namespaces
108BookBook talk109
442CourseCourse talk443
444InstitutionInstitution talk445
446Education ProgramEducation Program talk447
2300GadgetGadget talk2301
2302Gadget definitionGadget definition talk2303
2600Topic2601
Virtual namespaces
-1Special
-2Media
Current list

Lua is a lightweightscripting language that can be embedded intemplates through theScribuntoMediaWiki extension to create scripts on English Wikipedia. Since February 2013, Lua code has been available for use on the English Wikipedia via the{{#invoke:}} function. Scribunto currently supports Lua 5.1 as of October 2022[update].

On Wikipedia, Luasource code is stored on pages called modules in the modulenamespace (e.g., the source code for a module named "Example" would be atModule:Example). Individual modules are then invoked, using thesyntax{{#invoke:<Module name>|<Function name>|(optional) param1 |param2...}}, for example:

WikitextResult
{{#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 totemplate syntax, but with some differences. The most important difference is that you need to specify afunction name. Afunction is a set of instructions that take inputted values, processes them, and returns an output value.[1] This is much like what a template does: one gives itparameters, 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 cannot 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 does not do anything by itself. So there are two reasons that we need to input a function name: we cannot 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 runModule:Example in this way, which has a function named "hello".

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

Using arguments

Arguments, also known as parameters, are passed to modules in the same way that they are passed to templates. Note, however, that the text after the firstpipe character (|) is always the function name; the firstpositional argument (named parameter) is the text after thesecond pipe.

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

InModule:Example, thehello_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 inModule:Example, namedcount_fruit, uses the named argumentsbananas andapples 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 adocumentation page explaining what arguments can be used and what their effects will be.

In VisualEditor

Tracked inPhabricator
Task T205197
Open

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

VisitWikipedia 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

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

Discussed for years, Lua was installed in 2012 for testing ontest2.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 alsoBrad Jorsch's short presentation for a basic example of how to convert a wikitext template into a Lua module.

Lua is ascripting language which can be used to analyze data, calculate expressions, and format results using functions orobject-oriented programming. Although some Lua scripts can be kept simple, for easy understanding, Lua allows complex structures including tables, dynamic functions, andassociative arrays where indexsubscripts can be words as well as index numbers. Lua also supportsrecursion 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.

--- Example module.-- @module example-- @alias plocalp={}--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.--- Hello world function-- @param {table} frame current frame-- @return Hello worldp.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.localstr="Hello World!"--Declare a local variable and set it equal to--"Hello World!".returnstr--This tells us to quit this function and send the information in--"str" back to Wikipedia.end-- end of the function "hello"--- Hello world function-- @param {table} frame current frame-- @param {string} frame.args[1] name-- @return Hello worldfunctionp.hello_to(frame)-- Add another functionlocalname=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 modulereturn"Hello, "..name.."!"-- `..` concatenates strings. This will return a customized-- greeting depending on the name given, such as "Hello, Fred!"end--- Counts fruit-- @param {table} frame current frame-- @param {string} frame.args.bananas number of bananas-- @param {string} frame.args.apples number of apples-- @return Number of apples and bananasfunctionp.count_fruit(frame)localnum_bananas=tonumber(frame.args.bananas)or0-- Named arguments ({{#invoke:Example|count_fruit|foo=bar}})localnum_apples=tonumber(frame.args.apples)or0-- are likewise accessed by indexing `frame.args` by name (`frame.args["bananas"]`,--  or equivalently `frame.args.bananas`.localconj_bananas=num_bananas==1and'banana'or'bananas'localconj_apples=num_apples==1and'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--- Lucky function-- @param {string} a-- @param {string} b-- @return Whether a is lucky.returnp--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), seemw:Extension:Scribunto/Lua reference manual.

Unit testing

See also:Category:Modules for test tools

A fewunit 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 detectingsoftware regressions, where modifications to a script introduce new (or identify old) problems.

By convention, unit tests for a module likeModule:Example are placed inModule:Example/testcases, and are executed onModule 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.

For testing and step-by-step debugging of Lua modules outside of MediaWiki you can try using anmw mock (should work for all simple modules and maybe even some complicated ones).

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 (seemw: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 bypage 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 doesnot 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 acategory, nor the contents ofnon-transcludeablespecial 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 thepipe 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>. Useframe:extensionTag to add tags like<ref> or<syntaxhighlight> to output.

Labeling converted templates

This template usesLua:

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. ^One can also have multiple output values, but functions that do this are not normally meant to be accessed from wiki pages.
General
technical help
Special
page
-related
Wikitext
Links anddiffs
Media files: images,
videos and sounds
Other graphics
Templates and
Lua modules
Data structure
HTML andCSS
Customisation
and tools
Automated editing
Retrieved from "https://en.wikipedia.org/w/index.php?title=Wikipedia:Lua&oldid=1309350474"
Categories:
Hidden category:

[8]ページ先頭

©2009-2025 Movatter.jp