Jump to content

Wikipedia:Lua

From Wikipedia

Lua be one safe programming language wey people fit put inside templates through de Scribunto MediaWiki extension, so dem fit create scripts for de Ghanaian Pidgin Wikipedia. Since February 2013, people fit use Lua code for de Wikipedia through #invoke: Scribunto dey support Lua 5.1.

Accra for Lua

[edit source]

You no need install or save anything.

  1. Edit your user page.
  2. Paste de two calls below for de beginning of a new line for your user page:
{{#invoke:Location map|main|pushpin_map=Ghana|caption=[[Accra]], West Africa|label=Accra|lat_deg=5.55|lon_deg=-0.2|width=630}}
{{#invoke:Location map|main|Ghana|caption=Ghana, Gulf of Guinea, Africa|label=Accra|lat_deg=5.55|lon_deg=-0.2|float=none|relief=1}}
  1. Click Show preview. De function call main for de Module:Location map go change to de ones below:
Accra is located in Earth
Accra
Accra
Accra is located in Ghana
Accra
Accra
Ghana, Gulf of Guinea, Africa
  1. Click Cancel. When dem ask you, click Leave.
  2. Your user page no change.

Debug console: Start learn Lua

[edit source]

De Lua Scribunto Debug Console be safe, interactive tool wey you fit use learn Lua for Wikipedia.

  1. Click View source for de Module:Yesno page.
  2. Scroll go de bottom of de page reach de Debug console section.
  3. Paste de comment den de call for de gray input box (above de Clear button).
--[[Your very first Lua Hello World-like program]]--
print("Welcome to " .. _VERSION .. "!") -- Join de Lua version with `..`
  1. Press ↵ Enter one time to run de two Lua commands.
  2. De result go show below de Lua print command line:
Welcome to Lua 5.1!
  1. Press ↑ Up arrow to move through de Lua commands wey you use before.
  2. If you want, click Clear to clear only de Debug Console; de Lua editor wey dey above go remain unmodified.


Identity function

callParserFunction #if

--[[#if yesno then e dey return de input parameter]]--
local yesno = require('Module:Yesno')
print(mw.getCurrentFrame():callParserFunction("#if", yesno("Yes"), "Yes", 'no'))
print(mw.getCurrentFrame():callParserFunction("#if", yesno('no'), "Yes", 'no'))
Yes
no
  1. Close de protected Module:Yesno wey remain unmodified.


ASCII (Gpe) vs. Unicode (Twi Akan)

Dem recommend say make you use de mw.ustring.len function instead of de string.len one.

Inside de Debug console for Module:Yesno:

--[[:en:ASCII]]--
local content_lang = mw.getContentLanguage().code
print("content_lang: " .. content_lang)
local lang = mw.getCurrentFrame():callParserFunction("#language", content_lang)
local lenUnicode = mw.ustring.len(lang) -- number of characters
local lenByte, lenSharp = string.len(lang), #lang -- length in byte
print(("lang: \"%s\" Mw.ustring.len = %d String.len = %d Sharp = %d"):format(lang, lenUnicode, lenByte, lenSharp))

--[[:en:Unicode]]--
lang = "Ɛyɛ, we go go." -- Okay (Twi), we'll go (Gpe)
lenUnicode = mw.ustring.len(lang)
lenByte, lenSharp = string.len(lang), #lang
print(("lang: \"%s\" Mw.ustring.len = %d String.len = %d Sharp = %d"):format(lang, lenUnicode, lenByte, lenSharp))

De debug console dey support Unicode:

content_lang: gpe
lang: "Ghanaian Pidgin" Mw.ustring.len = 15 String.len = 15 Sharp = 15
lang: "Ɛyɛ, we go go." Mw.ustring.len = 14 String.len = 16 Sharp = 16

For your user page:

{{#invoke:Utf8debug|ek|Ɛyɛ.}}
number of
octet:s : 6


index 0
beg code $C6=#198
length 2
extra $90
codepoint U+$0190
dec #400
 Ɛ 
index 2
beg code $79=#121
length 1
 y 
index 3
beg code $C9=#201
length 2
extra $9B
codepoint U+$025B
dec #603
 ɛ 
index 5
beg code $2E=#46
length 1
 . 


number of UTF8
char:s : 4

Using arguments

[edit source]

For your user page:

{{#invoke:Trim quotes|trim|'Hey, how are you, tonight?'}}

Hey, how are you, tonight?


Inside de Debug console for Module:Yesno:

local exprQuote = "'Chalé, how you dey for gbekeh oo?'"
print(exprQuote)                        -- ^ Ga-derived
local modTrim = require('Module:Trim quotes')
local frame = mw.getCurrentFrame(); frame.args[1] = exprQuote
print(modTrim.trim(frame))
'Chalé, how you dey for gbekeh oo?'
Chalé, how you dey for gbekeh oo?


Named arguments |key=value

Inside de Debug console for Module:Yesno: frame:preprocess()

print("1. " .. tostring(mw.title.getCurrentTitle()))
print("2. " .. mw.getCurrentFrame():preprocess('{{PAGENAME}}'))
print("3. De reverse of \"UNIQ\" be: \"" .. string.reverse("UNIQ") .. '"')

print("4. Lua Scribunto be HTML generator:")
local wikitext = "{{#invoke:Location map|main|pushpin_map=Ghana|caption=Africa|label=Accra|lat_deg=5.55|lon_deg=-0.2}}"
print(mw.getCurrentFrame():preprocess(wikitext))
1. Module:Yesno
2. Yesno
3. De reverse of "UNIQ" be: "QINU"
4. Lua Scribunto be HTML generator:
<DEL>'"`UNIQ--templatestyles-00000000-QINU`"'<DEL><div class="locmap noviewer noresize thumb tright"><div class="thumbinner" style="width:242px"><div style="position:relative;width:240px;border:1px solid lightgray">[[File:World location map (equirectangular 180).svg|240px|Accra is located in Earth|class=notpageimage]]<div class="od notheme" style="top:46.917%;left:49.944%;font-size:91%"><div class="id" style="left:-4px;top:-4px">[[File:Red pog.svg|8x8px|Accra|link=|class=notpageimage]]</div><div class="pr" style="width:6em;left:5px"><div>Accra</div></div></div></div><div class="thumbcaption"><div class="magnify">[[:File:World location map (equirectangular 180).svg|class=notpageimage| ]]</div>Africa</div></div></div>

Code wey dem hide "UNIQ--templatestyles-00000000-QINU" wey dey between non-printing 0x7F DEL markers, dem strip am out with "<DEL>".

local modMap = require('Module:Location map')
local tablePrm = {pushpin_map="Ghana", caption="Africa", label="Accra", lat_deg="5.55", lon_deg="-0.2"}
local frame = mw.getCurrentFrame(); frame.args = tablePrm
print(modMap.main(frame))

De HTML wey e generate be di same.

Debugging Lua

[edit source]

Inside de Debug console for Module:Yesno:

local tableGhana = require('Module:Location map/data/Ghana')
print("mw.logObject(tableGhana) dey display one item for each line:")
mw.logObject(tableGhana) -- Scribunto tool to display table

print("Custom debugLog dey display de items for de same line:")
local debugLog = {} -- empty report table
for key, val in pairs(tableGhana) do -- for each key
    debugLog[#debugLog + 1] = ("[%s]=%s"):format(key, val)
end --       ^length. Adding report is faster than string-based:
--            debugLog = debugLog .. string
print(table.concat(debugLog, " ")) -- Join with space separator
mw.logObject(tableGhana) dey display one item for each line:
table#1 {
    ["bottom"] = 4.5,
    ["image"] = "Ghana adm location map.svg",
    ["image1"] = "Ghana physical map.svg",
    ["left"] = -3.6,
    ["name"] = "Ghana",
    ["right"] = 1.5,
    ["top"] = 11.4,
}
Custom debugLog dey display de items for de same line:
[top]=11.4 [image]=Ghana adm location map.svg [name]=Ghana [bottom]=4.5 [right]=1.5 [left]=-3.6 [image1]=Ghana physical map.svg

Portal

[edit source]

Scroll go de bottom of de page Issa Laye Thiaw:

Template:Serer topics Template:Pan-Africanism Lua error: bad argument #2 to 'title.new' (unrecognized namespace name 'Portal').

Namespace 100: Portal

For your user page: reproduce de issue

{{Portal bar|Senegal|Gambia|History|Religion}}

Lua error: bad argument #2 to 'title.new' (unrecognized namespace name 'Portal').

Click for see de call stack error message:

  1. Module:Portal_bar#L-45 portals, trackingCat = checkPortals(portals, args)
  2. Module:Portal#L-164 local portalTitle = mw.title.new(portal,"Portal")


mw.title.new(text, namespace)

Wetin be de value of de first parameter, de lowercase variable portal?

Instrument temporarily Module:Portal without saving:

  1. Click Edit
  2. After do, add one temporary call to error(msg)
for _, portal in ipairs(portals) do error("portal = " .. portal)
    local portalTitle = mw.title.new(portal,"Portal")
  1. Make sure say you do NOT click "Publish changes"
  2. Under "Preview page with this template", paste de wiki page name of de caller:
Issa Laye Thiaw
  1. Click Show preview.
  2. Scroll go de end of "References". De error line number go turn 163:

Template:Serer topics Template:Pan-Africanism Lua error in Module:Portal at line 163: portal = Senegal.

  1. Click "Cancel"


Inside de Debug console for Module:Yesno:

--[[Display each namespace ID and its canonical name]]--
local namespaces = mw.site.namespaces; local countNs = 0
for namespaceId, namespace in pairs(namespaces) do
    print(namespaceId .. ": " .. tostring(namespace["canonicalName"]))
    countNs = countNs + 1
end
print("Number of namespaces: " .. countNs)
1: Talk 2: User 3: User talk 4: Project 5: Project talk 6: File 7: File talk
8: MediaWiki 9: MediaWiki talk
10: Template 11: Template talk 12: Help 13: Help talk
14: Category 15: Category talk
0: 

828: Module

710: TimedText 1728: Event -1: Special -2: Media 829: Module talk
711: TimedText talk 1729: Event talk

Number of namespaces: 24

Compare this wit de output from de Debug console of en:Module:Yesno. You go find 30 namespaces, including 100: Portal.

Temporary workaround for Issa Laye Thiaw page: comment out de call to Template:Portal bar:

<!-- {{Portal bar|Senegal|Gambia|History|Religion}} -->

Solution:

To use Wikipedia portal technology:

  1. See de requirements.
  2. Ask administrator to create custom namespace ID 100: Portal, by adding am to $wgExtraNamespaces inside LocalSettings.php.

Harvard citation

[edit source]

Template:Harvnb: "nb" mean No Bracket, wey mean without parenthesis.

Slavery in Africa: "Philippines during Iberian Union (1580-1640).": click reference [166].

Inside de Debug console for Module:Yesno:

local wikitext = "{{Harvnb|Allen|2017|loc=Slave Trading in the Indian Ocean: An Overview, pp. 295–299}}"
print(mw.getCurrentFrame():preprocess(wikitext))

Errors dey two: de wikilink no generate. |loc= dey ignore am wrongly:

<span id="CITEREFAllen2017"><b>Allen</b>, 2017</span>

You fit add de location after de page number |p=:

local wikitext = "{{Harvnb|Allen|2017|p=295–299 Slave Trading in the Indian Ocean: An Overview}}"
print(mw.getCurrentFrame():preprocess(wikitext))
<span id="CITEREFAllen2017"><b>Allen</b>, 2017, p. 295–299 Slave Trading in the Indian Ocean: An Overview</span>

Harvard inside parenthesis Template:Harv dey work better:

local wikitext = "{{Harv|Allen|2017|p=295–299|loc=Slave Trading in the Indian Ocean: An Overview}}"
print(mw.getCurrentFrame():preprocess(wikitext))

Debug console fit show more information:

anchor_id_list = table#1 {
}
template_list = table#1 {
    ["Yesno"] = 1,
}
article_whitelist = table#1 {
}
citeref_patterns = table#1 {
}
no target: CITEREFAllen2017
([[#CITEREFAllen2017|Allen 2017]], p.&nbsp;295–299, Slave Trading in the Indian Ocean: An Overview)<span class="error harv-error" style="display: none; font-size:100%"> harv error: no target: CITEREFAllen2017 ([[:Category:Harv and Sfn template errors|help]])</span>

Prefer Short Foot Note Template:Sfn. Sfn short pass Harvard citation:

  1. <ref>{{Harv|Allen|2017|p=295–299}}</ref> is equivalent to:
  2. {{sfn|Allen|2017|p=295–299}}. It does not need <ref> and </ref> tags.


Template den module

[edit source]

A module template na shortcut wey simplify calls to dat module.

For your user page: Template:Convert dey call convert function of Module:Convert

{{convert|123|lb|kg}}

123 pounds (56 kg)

Inside de debug console for Module:Yesno:

local modConv = require('Module:Convert')
local frame = mw.getCurrentFrame(); frame.args = {"123", "lb", "kg"}
print(modConv.convert(frame))

De most common error dey related to nil:

Lua error in Module:Convert at line 3718: attempt to index a nil value.

Module:Convert dey retrieve dis parameters with frame:getParent()

local success, result = get_parms(parms, frame:getParent().args)


Build de frame with parameters for de template at de parent level:

local function buildFrame(templateTitle, parentArgs, moduleName, childArgs)
    local root = mw.getCurrentFrame()
    local parent = root:newChild{title=templateTitle, args=parentArgs or {}}
    return parent:newChild{title=moduleName, args=childArgs or {}}
end
local tablePrm = {"123", "lb", "kg"} -- parameters at de template's parent level
local templateName = 'Template:Convert'; local moduleName = 'Module:Convert'
local frame = buildFrame(templateName, tablePrm, moduleName) -- childArg is nil
local modConv = require(moduleName)
print(modConv.convert(frame))
123 pounds (56&nbsp;kg)

Cite book

[edit source]

For your user page: Template:Cite book dey call citation function of Module:citation/CS1 with child parameter |CitationClass=book

{{Cite book |last=Wilson |title=History of the British Expedition to Egypt |year=1803}}

Wilson (1803). History of the British Expedition to Egypt.

Inside de Debug console for Module:Yesno:

local function buildFrame(templateTitle, parentArgs, moduleName, childArgs)
    local root = mw.getCurrentFrame()
    local parent = root:newChild{title=templateTitle, args=parentArgs or {}}
    return parent:newChild{title=moduleName, args=childArgs or {}}
end
local tablePrm = {last='Wilson', title='History of the British Expedition to Egypt', year='1803'}
local childArg = {CitationClass="book"}
local templateName = 'Template:Cite book'
local moduleName = 'Module:citation/CS1'
local frame = buildFrame(templateName, tablePrm, moduleName, childArg)
print(require(moduleName).citation(frame))
<DEL>'"`UNIQ--templatestyles-00000000-QINU`"'<DEL><cite id="CITEREFWilson1803" class="citation book cs1">Wilson (1803). ''History of the British Expedition to Egypt''.</cite><span title="ctx_ver=Z39.88-2004&rft_val_fmt=info%3Aofi%2Ffmt%3Akev%3Amtx%3Abook&rft.genre=book&rft.btitle=History+of+the+British+Expedition+to+Egypt&rft.date=1803&rft.au=Wilson&rfr_id=info%3Asid%2Fgpe.wikipedia.org%3AModule%3AYesno" class="Z3988"></span>

See Template:Sfn for Rosetta Stone: "Menou surrender on 30 August."[42]

"#CITEREF" + Author "Wilson" + Year of de book "1803" be de anchor wey link go de book: Rosetta Stone#CITEREFWilson1803

Read further

[edit source]