This page is an archive of past discussions. Do not edit the contents of this page. If you wish to start a new discussion or revive an old one, please do so on the current talk page. |
Template ( https://ru.wikipedia.org/wiki/Шаблон:Население https://ru.wikipedia.org/wiki/Модуль:Statistical ) provides information for the users in numbers and graphs about the population. On the one hand, we have population censuses and data for different years. On the other hand, we call this data through a template simply by specifying the name of the city. But there are many thousands of cities. Working through lua-modules, we made a unique hash of the name of the city and, by a unique hash, we further searched for numbers on the population. But these are >60 tables of 3000 elements ( https://ru.wikipedia.org/wiki/Шаблон:Население/STA-061 ) for these unique hashes. lua mw.loadData results in maximum use of the amount of memory allocated for lua. The hash was placed in the templates ( https://ru.wikipedia.org/?title=Модуль:Statistical&diff=83973924&oldid=82885634 ) and searched through the switch and expandTemplate. From 4th to 7th of June, 2019, we experienced problems that appeared apparently somewhere on the server side, because before and after this period it again appears without errors. Probably the slow work of a large switch results in maximum use of the work time allocated for lua. And further template calls for the public return the red text of the error "lua limit reached". Thus, it seems that we are somewhere on the verge of the possibility of the module / templates working. Could there be a faster or more practical way to work with such a large amount of data? -- Sunpriat ( talk) 11:02, 11 June 2019 (UTC)
{{#switch:}}
parser function in
ru:Шаблон:Население/STA-061 uses Lua resources (if I am not misunderstanding), it does not. Lua resources are only used by invocations of modules. Regardless of how much time the {{#switch:}}
parser function takes, the Lua invocations are allowed to run for up to 10 seconds. —
Eru·
tuon 05:00, 12 June 2019 (UTC)This will probably be a Herculean task, but I'm hoping someone can help me with this: Can someone possibly get {{
Calendar}} "Lua-ized" via a module at
Module:Calendar? Asking since ...
something I'm trying to do ran across expensive call template include size issues. So ... I'm really hoping this can be accomplished.
Steel1943 (
talk) 00:27, 29 June 2019 (UTC)
{{
calendar}}
.
Module:Calendar widget? Continue this discussion there?{{
ISOCALENDAR}}
has form and styling vaguely similar to {{
calendar}}
and to
Module:Current events calendar so could be a candidate for the widget.I've made a start with Module:Calendar widget, Template:Calendar widget and Template:Calendar widget/styles.css. There is some testing of the module at Module talk:Calendar widget/Testing. I threw in a couple of exported functions that check for a leap year and return what day of the week a particular date is. There's virtually no inline styling in the module, but all of the tables, rows, headers and data cells have a class set that can be styled via the template's template styles. I still have to implement most of the parameters available for Template:Calendar, but I'll have another look tomorrow if I get a chance. Please feel free to hack at it if you're interested. Cheers -- RexxS ( talk) 00:26, 30 June 2019 (UTC)
2000 | |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
|
|
|
| ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
|
|
|
| ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
|
|
|
|
So I broke it. I know how it's broken but am at a loss to know why.
I had thought to use the Scribunto HTML library because it seemed to me that support for variations in styling and whatever other sorts of options that might be wanted could more easily handled by that library. I haven't used the HTML library before so my own naivete might be mostly to blame for the broken code.
As you can see the individual monthly calendars aren't top-aligned as they should be. The style is properly included but the <tr>
tag that holds it is immediately closed:
<table class="ycal"><tr class="ycalhdr"><th class="ycal" colspan="4">2000</th></tr><tr class="ycal" style="vertical-align:top"></tr><td class="ycal">
For comparison, here is the original (stretched out to make it easier to compare):
<table class="ycal"><tr class="ycalhdr"><th class="ycal" colspan="4>2000</th><tr class="ycal" style="vertical-align:top;"><td class="ycal">
I notice that the original is, I think, missing a </tr>
after the <th>...</th>
tag.
What did I do wrong? Is it bad that I have only made this change to displayyear()
and not to displaymonth()
?
The original code remains but has been commented out and there is an mw.log()
that dumps the html output to the debug console log.
— Trappist the monk ( talk) 00:51, 1 July 2019 (UTC)
<table class="ycal"><tr class="ycalhdr"><th class="ycal" colspan="4">2000</th></tr><tr class="ycal"></tr><td class="ycal">
<tr style="vertical-align:top">
apply to the enclosed <td>...</td>
tags?<table class="ycal"><tr class="ycalhdr"><th class="ycal" colspan="4">2000</th></tr><tr class="ycal"><td class="ycal">
local year_row = year_cal
makes year_row
a new object, how does
year_cal
know anything about what gets added to year_row
? This suggests to me that year_row
and year_cal
are not separate objects but are 'pointers' or 'references' to the same 'thing'. If they are 'pointers' or 'references' then that explains why everything that got added to year_row
is present at the end when return tostring (year_cal)
. But that doesn't explain why it is necessary to indirectly add the <td>...</td>
tags via year_row
.year_row
is a pointer, why is it necessary?year_cal:tag('tr') year_cal:tag('td')
just adds tags as direct children of year_cal
. Calling local year_row = year_cal:tag('tr') year_row:tag('td')
adds a tr tag to year_cal
, returns it, saves a reference to it in the local variable (because the tag
method returns a new object for the tag that was created), and using this reference adds a td tag to it rather than to year_cal
. —
Eru·
tuon 13:36, 1 July 2019 (UTC)
<td>...</td>
tags that are required for each row into :wikitext()
because that is how (as I understand it) content is meant to be added to a tag. So I hacked a function that does the necessary work to create <td>...</td>
tags and called it from year_cal:wikitext()
. It works without confusing indirection.add_td_tags()
so that it can be used more broadly than it is now. I'll think on that.For example, if module was:
local str = "Hello World!" local p = {["string"] = str}; p.hello = function(frame) return str end return p
and the template code {{#invoke:moduleName|string}}
returned Hello World!
. Or do I have to create a function if I want to achieve that? —
andrybak (
talk) 08:34, 5 July 2019 (UTC)
local
outside functions. The main concern is performance – too much global stuff slows execution down; it is better to resort to
require(modulename) in the case where heavy initialized data are desirable.
Incnis Mrsi (
talk) 09:56, 5 July 2019 (UTC)X
in {{#invoke:moduleName|X}}
has to be a function name, or whether it could be a code (such as "string") to get the code's value (such as "Hello World!"). The answer is yes it can be a code, but it's pretty ugly and involves setting a metatable on p
such that X
is interpreted at runtime. A lot less hair would be lost if the call were {{#invoke:moduleName|get|X}}
where the function get
returns the value for X. See
Module:Data for how magic metatable code can be written.
Johnuniq (
talk) 10:43, 5 July 2019 (UTC)Hello, I have few connoissances into Lua. I have (one) (or multiple words) into a given string. Example : <CDG LAX JFK> (string without the < and the >) I would need this string transformed into %22CDG%20LAX%20JFK%22 so that this being understandable by a sparql query. I have written a short code but it doesn't come the fashion I need. Any tip would be greatly appreciated. -- Bouzinac ( talk) 20:16, 23 July 2019 (UTC)
local p = {}
s=frame.args1
function p.recode(frame)
return "%22".. s:gsub(" ","%20").. "%22"
end
return p
local p = {}
function p.recode(frame)
return "%22" .. mw.uri.encode(frame.args1],"PATH") .. "%22"
end
return p
local function transform(s)
return mw.uri.encode(s:gsub("%S+", '"%1"'), "PATH")
end
function p.transform(frame)
return transform(frame.args1])
end
I'm trying to use the ParserFunctions library in lua for it's trunc() calculation, but
Help:Extension:ParserFunctions has no documentation at all how its used other than mw.ext.ParserFunctions.expr
. The most I was able to get is mw.ext.ParserFunctions.expr("trunc", value)
but that gives me the error "Lua error: Expression error: Missing operand for trunc..". Any ideas? --
Gonnym (
talk) 07:43, 24 July 2019 (UTC)
local success, result = pcall(mw.ext.ParserFunctions.expr, 'trunc 1234.5678') if success then -- result is the result else -- result is error text end
local input = 1234.5678
local truncated = math.floor(input) -- returns the same as mw.ext.ParserFunctions.expr('trunc ' .. input)
input = '1234.5678' -- works for strings, too:
truncated = math.floor(input) -- still 1234: i guess math.floor is nice enough, and calls tonumber() for you, or something. JS behave similarly
-- math.floor will throw if the parameter is not "numberable", e.g. "bla", '', or nil. you can use pcall, or test directly:
local num = tonumber(input)
if num then -- safe: in lua, 0 evaluates to true
truncated = math.floor(num)
else
-- do some error handling
end
trunc 1234.5678
or or trunc(1234.5678)
. this looks a bit bizarre (why would the editor pass something like this as a parameter?), but i guess it's possible. peace -
קיפודנחש (aka kipod) (
talk) 19:34, 24 July 2019 (UTC)
I have an array of arithmetic expressions as strings and I need to do a calculation with an x value for the relevant one, however it can't do that with an arithmetic expression as a string. I'd like to avoid needing to do this as an if/else. Any ideas? Code below:
local function main(value1, value2)
local arithmeticExpressionList = {
1 = " % 2 + 4",
4 = " / 2 % 2 + 2",
6 = " / 4 % 2 + 5",
9 = " / 8 % 2 + 5",
12 = " / 16 % 2 + 3",
14 = " / 32 % 2 + 8",
17 = " / 64 % 2 + 6"
}
local arithmeticExpression = arithmeticExpressionListvalue1
if (arithmeticExpression) then
value = value2 .. arithmeticExpression
return value
end
end
-- Gonnym ( talk) 06:51, 25 July 2019 (UTC)
value = value2 .. arithmeticExpression
should be the same result as value = 7 % 2 + 4
. % is
Modulo operation. --
Gonnym (
talk) 07:36, 25 July 2019 (UTC)local function main(value1, value2)
local arithmeticExpressionList = {
1 = function ( x ) return x % 2 + 4 end,
4 = function ( x ) return x / 2 % 2 + 2 end,
6 = function ( x ) return x / 4 % 2 + 5 end,
9 = function ( x ) return x / 8 % 2 + 5 end,
12 = function ( x ) return x / 16 % 2 + 3 end,
14 = function ( x ) return x / 32 % 2 + 8 end,
17 = function ( x ) return x / 64 % 2 + 6 end
}
local arithmeticExpression = arithmeticExpressionListvalue1
if (arithmeticExpression) then
return arithmeticExpression( value2 )
end
end
Hey, I can't see how to get an exact match. I am using [Cc]hess in a template, looking to get back only the full-word matches of " Chess " and " chess ", but I of course also get "duchess", "duchesses", "Chessie", etc. What pattern code returns only the selected characters when they are surrounded by spaces, and not part of a larger word? Thanks in advance. UnitedStatesian ( talk) 12:53, 20 August 2019 (UTC)
%f[%a]([Cc]hess)%f[%A]
%a
matches all letters, while %A
does the opposite (it matches all non-letters).
Johnuniq (
talk) 04:05, 23 August 2019 (UTC)
some of the examples on Module:InfoboxImage aren't showing any image at all, and I don't know if it's just my laptop. I tried having a look at the source but I know absolutely nothing about code so I don't know what's wrong or how to fix it... Snizzbut ( talk) 15:48, 30 September 2019 (UTC)
|suppressplaceholder=no
flag, and one uses an image that doesn't exist. I think that's correct. Do you see more than five examples without images?
Certes (
talk) 15:54, 30 September 2019 (UTC)
After mastering "hello world" my next stepping stone is code to get information for a given URL (PageSize for starters). Can some good soul turn my head in the right direction? TiA Vitosmo
Because I'm improving a fairly complex module (more than two thousand lines of code). I created this module to make easy the debugging of any other module, because the Debug console is not always useful enough.
Also I added a new chapter: Help:Lua_debugging#How_debug to explain the possibilities of debugging. Maybe it would be interesting to improve and/or correct it (since my English level is intermediate).
-- Jmarchn ( talk) 21:12, 22 October 2019 (UTC)
I'm not exactly sure what is going on, so I created a simplified example. I start with the base full table in
User:Frietjes/l which transcluded in
User:Frietjes/l1,
User:Frietjes/l2, and
User:Frietjes/l3. The problem appears in
User:Frietjes/l1 which has an efn (in the ghost references section) that does not appear in the article. I think I have isolated it to the tracking, since if I turn the tracking off, I get
User:Frietjes/l3 which doesn't have any ghost references. any idea how to get the tracking to work without showing the ghost references? feel free to make changes to
Module:Sandbox/Frietjes and/or Module:Sports table/argcheck/sandbox if you have ideas on how to fix it.
Frietjes (
talk) 17:45, 1 November 2019 (UTC)
|notracking=
) add notes for the whole table, including one for Ipswich who don't make the table due to finishing more than four places behind Arsenal.
Certes (
talk) 18:32, 1 November 2019 (UTC)
local unused = args.text_IPS
, causes the footnote to appear. It seems that the #invoke:
magic in
mw:Extension:Scribunto only evaluates each parameter when first needed, so |text_IPS={{fb...{{efn...}} }}
only produces a footnote if someone looks at the value of args.text_IPS
. Footnote f in
Wikipedia:Guide to Scribbling provides minimal evidence for this theory.
Certes (
talk) 18:01, 3 November 2019 (UTC)uses
metatables to fetch arguments from #invoke ... without using the pairs()
function
.
Certes (
talk) 18:08, 3 November 2019 (UTC)
args.foo
or args["foo"]
with an argument table output from
Module:Arguments, then pairs() isn't called on the original #invoke arguments. However, if you call pairs() on the argument table, each argument from #invoke is fetched using the next() function, which has the same effect as using pairs() on the original #invoke arguments. —
Mr. Stradivarius
♪ talk ♪ 01:40, 4 November 2019 (UTC)|text_IPS={{fb...{{efn...}} }}
evaluates as as part of the template expansion process; the module only sees the expansion of {{fb|...}}. That expansion has the side effect of creating a footnote but occurs only when Lua needs to determine the value of args.text_IPS
during
lazy evaluation. I'm not a veteran Lua coder, so please correct me if any of that is wrong!
Certes (
talk) 11:30, 4 November 2019 (UTC)
if key == "text_IPS" then return nil else return table[key] end
. Disappointingly, I can find no way to get a list of keys without evaluating their values, even with heavy
metatable manipulation.
Certes (
talk) 18:48, 4 November 2019 (UTC)
Is there a way to get the name of a variable in Lua? My use-case, I have a list of parameters passed via a template to a module and they differ by a suffix letter. I need to sum the values of all variables that end with the same letter together.
So for this local args = {arg1W = 2, arg1L = 3, arg2W = 3, arg2L = 5}
, is it possible to get the string value of the parameter names (know that args1W is "args1W")? --
Gonnym (
talk) 13:55, 20 November 2019 (UTC)
args
member of the parent frame so you can:
local parent_args=mw.getCurrentFrame():getParent().args
for param_name, param_val in pairs (parent_args) do ... end
local sums = {}
for param_name, param_val in pairs (parent_args) do
local letter = param_name:sub(-1)
sumsletter = (sumsletter or 0) + param_val
end
for k, v in pairs(sums) do
-- do something: k is the letter, v is the sum for that letter
end
-- or just use sums.W and sums.L if you know what sufix letters are going to be passed
The result of the move request was: No consensus to move the listed talk pages. While some of the participants agreed there was no harm in moving the talk pages, most felt that it made more sense to discuss changes to a module on the module's talk page. In total there were no strong opinions in either direction, so the status quo will be maintained. Primefac ( talk) 13:25, 23 November 2019 (UTC)
– Modules that are used solely to implement one template are internal stuff; the actual non-programmer-facing page is the template, so any discussion about the template should happen on the template talk page, not the module talk page. * Pppery * it has begun... 22:10, 8 November 2019 (UTC) —Relisting. Primefac ( talk) 13:14, 16 November 2019 (UTC)
If one of you Lua programmers could parametrize this for me, I'd very much appreciate it. The current hatnote seems rather derp when used in the context I've described and I'd rather not use custom hatnotes unless I have no other choice. Seppi333 ( Insert 2¢) 17:05, 30 November 2019 (UTC)
I'm trying to make a template that helps with TemplateData (basically, makes it a bit less complicated to do and has it in template form. User:Lemondoge/templatedata) Currently it only supports 3 parameters, and I am trying to figure out how to make it support infinitely many parameters. I have an unfinished module page for it ( Module:Sandbox/Lemondoge/templatedata), but I can't figure out how to make it work - already stuck on how to concatenate arguments to create JSON format. Any help? (See template page and documentation for information on the usage of the template in its current state.) {{ Lemondoge| Talk| Contributions}} 19:45, 2 December 2019 (UTC)
|label1=
, |param1=
, |description1=
, |type1=
, |status1=
; then |label2=
, ... etc.require('Module:No globals');
local getArgs = require ('Module:Arguments').getArgs;
local function function_that_does_stuff (label, param, description, ptype, status)
local result
-- wherein stuff gets done that sets result
return result
end
local function templatedata (frame)
local args=getArgs (frame)
local final_result
local i=1
while frame.args'label'..i do
local result = function_that_does_stuff (args'label'..i], args'param'..i], args'description'..i], args'type'..i], args'status'..i])
-- here do something with result to fill final_result
i = i + 1;
end
-- here do something to finish off final_result
return final_result
end
return templatedata
local final_result = "poof"
), the template will do nothing, regardless of parameters. Current code is:
require('Module:No globals');
local getArgs = require ('Module:Arguments').getArgs;
local p = {}
local function function_that_does_stuff (label, param, description, ptype, status)
local result
result = '"'..param..'": { "label": '..label..'", "description": "'..description..'", "type": "'..ptype..'", "required": '..status..' },'
return result.."poof"
end
function p.templatedata (frame)
local args=getArgs (frame)
local final_result
local i=1
while frame.args'label'..i do
local result = function_that_does_stuff (args'label'..i], args'param'..i], args'description'..i], args'type'..i], args'status'..i])
final_result = final_result..result
i = i + 1;
end
return final_result
end
return p
Hi, I just continue with Lemondoges request - which does not bear an answer to my problem:
But at the moment I am not able to perform a repetitive frame:expandTemplate{ title = title, args = }
where the argument[s] are one after the other the values from a loop;
Lua seems to allow only one frame:expandTemplate{}
as the only one return value?
When that is the concept of Lua, this restriction should be expanded, because there are numerous templates having problems with long parameter lists! Poor code constructions like {{#if:{{{1|}}}|... until e.g. {{#if:{{{33|}}}|... will fail as soon as there are 34 parameters to handle. A loop in Lua can serve any uncountable number of parameters, when the repetitive transclusion is possible.
sarang♥
사랑 16:40, 14 January 2020 (UTC)
{{{1}}}
... {{{n}}}
then you might write something like this (untested and presuming that you have extracted an args table from the appropriate frame):
local out = {}
for i, v in ipairs (args) do
table.insert (out, frame:expandTemplate{ title = title, args = v })
end
return table.concat (out)
Another thing I cannot find information about: sure there must be an access to the system variables (of course it can be passed by a template, but how con I get it directly by the Lua code); how can I get e.g. environment parameters like the {{PAGENAME}} where the code is executed? sarang♥ 사랑 12:25, 19 January 2020 (UTC)
mw.title.getCurrentTitle().text
do what you want? If you are looking for the name of the module then frame:getTitle()
. Have you looked in
mw:Extension:Scribunto/Lua reference manual?Please see Template talk:Trim quotes#Wikimarkup interference. Trying to get Lua to do this gives me a headache, though I could do it easily in bash or Perl or whatnot. Lua just hasn't sunk in yet. — SMcCandlish ☏ ¢ 😼 21:35, 30 January 2020 (UTC)
I just created Module:Is_stub for merging {{ uncategorized stub}}. It detects if a page is tagged with a stub tag or not with a very high accuracy. Could someone please tell me either point me to the existing template for this purpose or tell me why this is a bad idea. I won't believe that this is the first time someone have thought of this. ‑‑ Trialpears ( talk) 21:54, 30 January 2020 (UTC)
{{#if:{{#invoke:String|match|{{#invoke:Page|getContent|{{FULLPAGENAME}}|as=raw}}|stub|ignore_errors=1}}|yes|no}}
does the exact same thing without creating more module bloat.
* Pppery *
it has begun... 00:17, 31 January 2020 (UTC)
You are invited to join the discussion at Wikipedia:Templates for discussion/Log/2020 February 13#Module:HelloWorld. * Pppery * it has begun... 22:28, 13 February 2020 (UTC)
You are invited to join the discussion at Wikipedia:Help_desk#Why_do_so_many_commonly-used_templates_use_MODULES?_When_they_don't_need_to?. * Pppery * it has begun... 01:15, 15 February 2020 (UTC)
Hi All,
Please have a look at my proposal and contribute with your opinions: Wikipedia:Village_pump_(proposals)#Connecting_Wikipedia_articles_to_reliable_sources_through_new_template
Thanks, Adam Harangozó ( talk) 14:14, 23 February 2020 (UTC)
Hi! Is there a way to get the list of pages in a category within a Lua module? I checked the Lua reference manual carefully, thought about it and tried a few things, but no luck, so before giving up I thought about asking here. Thanks! Sophivorus ( talk) 19:15, 23 March 2020 (UTC)
<math>...</math>
tags from the math strip marker using mw.text.unstripNoWiki()
. That was, and still is important to me because the content of <math>...</math>
tags is rendered as images. cs1|2 creates metadata for use by
Zotero and other reference management software. But, the metadata doesn't accept the transient images that mediawiki uses to render the equation. For the metadata, cs1|2 used to get the content of the math strip marker and extracted the original source equation from the <math>...</math>
tags for use in the metadata. But, mediawiki took away that ability so now, metadata for article titles with equations use MATH RENDER ERROR text in place of the equation (better that than as percent encoded version of the strip marker).Per this discussion at the VPT (start reading at "related idea"), we'd like to have a module that can take as input a given page and return the text from the {{ Nutshell}} on that page if one exists (and return "null" or something if the page doesn't have a nutshell). Would that be possible to create without too much effort? {{u| Sdkb}} talk 21:14, 4 April 2020 (UTC)
{{
nutshell}}
template in the target page, I think that can be done. But shortcuts often link to sections that don't have {{nutshell}}
and for for those that do the search has to be constrained to that section and you have to look for {{nutshell}}
and all of its redirects:
{{
Essay in a nutshell}}
{{
Guideline in a nutshell}}
{{
Guideline one liner}}
{{
In a nutshell}}
{{
Inanutshell}}
{{
Naming convention in a nutshell}}
{{
Nutshell2}}
{{
Policy in a nutshell}}
{{
Policy proposal in a nutshell}}
{{
Proposal in a nutshell}}
Improve pages wherever you can, and do not worry about leaving them imperfect. Preserve the value that others add, even if they "did it wrong" (try to fix it rather than [[WP:Deletion policy|delete it]]).
[[WP:EP|<span title="Improve pages wherever you can, and do not worry about leaving them imperfect. Preserve the value that others add, even if they 'did it wrong' (try to fix it rather than [[WP:Deletion policy|delete it]]).">WP:EP</span>]]
{{
nutshell}}
redirect patterns with whitespace; works well with ipairs()
:
local redirects_nutshell_patterns = {
'{{%s*[Nn]utshell%s*|',
'{{%s*[Ee]ssay in a nutshell%s*|',
'{{%s*[Gg]uideline in a nutshell%s*|',
'{{%s*[Gg]uideline one liner%s*|',
'{{%s*[Ii]n a nutshell%s*|',
'{{%s*[Ii]nanutshell%s*|',
'{{%s*[Nn]aming convention in a nutshell%s*|',
'{{%s*[Nn]utshell2%s*|',
'{{%s*[Pp]olicy in a nutshell%s*|',
'{{%s*[Pp]olicy proposal in a nutshell%s*|',
'{{%s*[Pp]roposal in a nutshell%s*|',
}
local function wikilink_strip (template)
for wikilink in template:gmatch ('%[%b[]%]') do -- get a wikilink
if wikilink then
template = template:gsub ('%[%b[]%]', '__57r1P__', 1); -- install a marker
if wikilink:match ('%[%[.-|(.-)%]%]') then
wikilink = wikilink:match ('%[%[.-|(.-)%]%]'); -- extract label from complex [[link|label]] wikilink
else
wikilink = wikilink:match ('%[%[(.-)%]%]'); -- extract link from simple [[link]] wikilinks
end
wikilink = escape_lua_magic_chars (wikilink); -- in case there are lua magic characters in wikilink
template = template:gsub ('__57r1P__', wikilink, 1); -- replace the marker with the appropriate text
end
end
return template;
end
if wikilink then
may not be necessary. I think it is a left-over artifact from an earlier version of the code that did not work.|title=
? Ignore?find()
to find a particular nutshell pattern then, with the start position returned from find()
, use match ('%b{}', start)
to get the whole template.ustring
functions?{{nutshell}}
; it is not.Find a better module name.I'm not passionate about the name. You are welcome to give it another one.
Is it really necessary to use the ustring
functions?
Not anymore :)escape_lua_magic_chars()
Where is this defined, and how important is it?--[[--------------------------< E S C A P E _ L U A _ M A G I C _ C H A R S >----------------------------------
Returns a string where all of lua's magic characters have been escaped. This is important because functions like
string.gsub() treat their pattern and replace strings as patterns, not literal strings.
]]
local function escape_lua_magic_chars (argument)
argument = argument:gsub("%%", "%%%%"); -- replace % with %%
argument = argument:gsub("([%^%$%(%)%.%[%]%*%+%-%?])", "%%%1"); -- replace all other lua magic pattern characters
return argument;
end
wikilink_strip()
because something that was being stripped had a percent-encoded space (%20
) in it that caused lua to choke because it saw that as a capture reference that it had not captured. You may never encounter that problem. I don't remember why I separated the %
escape from the rest of the lua magic characters. I've had no reason to change it because it has been working since I don't remember when.{{
WP|BOLD}}
. But maybe the WP should just be a shortcut and the template itself should be given a better name.
Pppery, I'm having some trouble getting {{
Template parameter value}} to work correctly. Do you or anyone else know what I'm doing wrong at
User:Guywan/Test2? {{u|
Sdkb}}
talk 22:26, 7 April 2020 (UTC)
{{template parameter value|{{#invoke:Redirect|main|WP:BOLD}}|nutshell|1|1|1|1}}
{{template parameter value|{{#invoke:Redirect|main|WP:BOLD}}|Nutshell|1|1|1|1}}
|title=
.{{#invoke:WP | main | SIG }}
→
WP:SIG[[File:OOjs UI icon signature-ltr.svg|22px]]
(
) renders in the tooltip as 22px; what to do about that?{{
nutshell}}
template.@ Trappist the monk: Re image, it seems very rare for an image to be in a nutshell, so I'd say no. The alt text might occasionally work, but it's just as (if not more) likely to be missing or incomplete, which would just add to the confusion. The current solution of "[IMAGE]" at least alerts the reader that there's an image there and that they might just want to click through.
Re stubs, it seems perfectly possible that a stub would have a nutshell, so I don't see why we'd want to exclude them from the template. Maybe figure out the WP:FENCE aspect, but if there's nothing technical making it necessary, just get rid of it.
Re other namespace abbreviations,
Template:MOS, unlike
Template:WP, is taken, so it'd be hard to allow {{MOS|LEAD}}
, but
WP:LEAD works fine, and goes to the same place.
And I'm glad to see the page titles now being included! (Thanks for coding that!) I notice that it can get a bit confusing for some, as in WP:BITE seems to be talking about biting newcomers in a nutshell (lol) with the current Wikipedia:Please do not bite the newcomers in a nutshell: Do not be... Adding quotes around the title could fix that. We could also use a period or line break to make it clearer that the link goes to the page. Together with those changes, we'd have something like "Wikipedia:Please do not bite the newcomers". In a nutshell: Do not be... I'm also on the fence about whether to we should take out the "Wikipedia:" — do you think it adds enough to be worth including?
Oh, and one thing showing up in WP:NPOV and a few other test cases is that italics and bolding aren't being reflected. Do Wikipedia tooltips have the technical capability to handle formatting like that? (If so, it might be nice to bold the article title to help it stand out a bit.) {{u| Sdkb}} talk 19:45, 12 April 2020 (UTC)
{{
nutshell}}
. Just to prove that the stub search portion of that isn't broken,
this search finds about 2500 stub templates. Given these results, I'm going to delete that snippet of code. If it turns out that there is a reason for it being there, the code is in the history of the module so it can be dredged up and restored.{{WP|MOS:LEAD}}
) that would render as
MOS:LEAD (with the tool tip and dotted underlining). It is my understanding that MOS shortcuts are preferred for the manual of style. Maybe I'll hack something into this code to see how that would work.<b>...</b>
around the article title portion of the tooltip. Not surprisingly, html tags inside a title attribute inside a <span>
confused MediaWiki so the enclosing <span>...</span>
rendered as linked plain text (but the title was bold). Right now, we do nothing with the bold and italic markup so where it exists in the {{nutshell}}
text, it shows up as raw markup in the tooltip. Leave it because we all know what it means, or strip it?{{WP|Help:CS1}}
→
Help:CS1{{WP|Project:LEAD}}
→
Project:LEAD{{WP|mos:MED}}
→
MOS:MEDmain
function. I unified namespaces
and pseudo_namespaces
so we only have to lookup in one table. Namespace input like h
, H
, pRoJeCt
, and mOs
are 'normalised' to Help
, Project
, and MOS
. —
guywan (
talk •
contribs) 14:27, 14 April 2020 (UTC)
<namespace>:<title>
shortcuts into another namespace. Namespace names and aliases are case insensitive and separated from the shortcut's article title with the colon. The title portion must obey the same case-sensitivity rules as any other page title:
[[wp:MED]]
→
wp:BOLD works; nominal redirect (page ID: 1502969)[[wp:mED]]
→
wp:bOLD works; same redirect as above (page ID: 1502969) because of the first-character case-insensitivity rule[[wp:med]]
→
wp:bold works; another redirect from WP:Bold (page ID: 1502965)[[wp:mEd]]
→
wp:bOLd does not work; no redirectDoes anyone know how to look up " globalSiteId' of the wiki the code is running on? So "enwiki" on English wikipedia, "commonswiki" for Commons, etc. I am updating c:Module:Interwiki and would like to ensure that the module will not add link to itself, even if copied to other wiki. -- Jarekt ( talk) 19:39, 22 April 2020 (UTC)
{{#invoke:WikidataIB |globalSiteID}}
→ enwikimw.wikibase.getGlobalSiteId()
. Cheers --
RexxS (
talk) 19:58, 22 April 2020 (UTC)
Do really http://lua-users.org/wiki/ a resource included the Lua list here, does not use MediaWiki? :-? BoldLuis ( talk) 09:15, 18 May 2020 (UTC)
Is there a way in Lua, magic words or regular template syntax to get the Display title value of a page (which doesn't involve reading the page content)? Wondering since its a value shown in the Page information of a page. -- Gonnym ( talk) 07:56, 20 May 2020 (UTC)
{{FULLPAGENAME}}
to cause problems for your application?{{#invoke: WikidataIB |getSiteLink |qid=Q10044351}}
to get 'ICarly season 6'. Leaving out the |qid=
will use the connected article for the page: {{#invoke: WikidataIB |getSiteLink}}
→ .Display titleis the desired result then the wikidata won't work because the displayed title is: iCarly (season 6) – italics and first character lowercase. Even if it were possible to get the displayed title, how would it be returned?
''iCarly'' (season 6)
<i>iCarly</i> (season 6)
Please could someone help to create radio button functionality for switching between historical maps?
Currently Module:Location map gives the ability for a reader to switch between contemporary map views using radio buttons (see example on the right). For historical maps, comparing what an area looks like today to how it looked historically, there is no template or module which can do the same. It would benefit articles about historical settlements which look very different today (for example Tenochtitlan in Mexico City, Cahokia in St. Clair County, Illinois, Londinium in London and Lutetia in Paris). The best I have been able to come up with is the gif on the right, but it has been fairly derided as overly "distracting".
Would it be possible to extract the relevant code from Module:Location map into a new "Module:Image select" or similar? It doesn't need any of the other functionality (e.g. coordinates, labels) as it can all be covered by the buttons and captions.
Onceinawhile ( talk) 09:21, 24 June 2020 (UTC)
Right now Module:SimpleDebug is transcluded into Cynthia Brewer. My assertion is that we should avoid transcluding testing modules. Can someone see if they can remove that use from there? -- Izno ( talk) 15:01, 20 July 2020 (UTC)
require
in
Module:TNTTools because it did not appear to be used in that module.Throughout the motorsport we use mostly similar color schemes and tables. And in the popular motorsport we use and update the same data but we update it on the different pages doing more edits than we actually need. I made an intermediate solution but it is a bit clumsy. All motorsport community will be pleased if you help us to made a module for the motorsport tables (their common look here. P.S. Also we had two slightly different tables , but probably they also could have connection and receive updates from the same source template/module. The example of the cells from such tables below: {{F1R2020|HAM|HUN}}
1PF |
HUN 1 |
P.S.S. The issue with Module:Sports rbr table is that we can't add Template:F1 race position or bold/italics. Also we need a possibility to add extra column for positions and numbers (in the case of the teams' standings). Corvus tristis ( talk) 03:39, 26 July 2020 (UTC)
Hello. Is anyone able to help me sort out
Module:Election results/sandbox? I can't work out what I've done wrong to make {{
Election results/testcases}} go wrong for the latter two tables. I suspect it's something to do with the second elseif cand then
section. There are a few other functions I'd also like to add to it, which I was planning to do by trial and error, but if anyone has a bit of time to assist, I'd be most appreciative. Cheers,
Number
5
7 21:36, 2 August 2020 (UTC)
cand
and sc
don't appear to be initialized by your code (Lua inits them to nil) and both are globals. Generally not a good idea to have globals if they can be avoided. Consider adding require('Module:No globals')
at the top of your sandbox. It will help find (mis)used globals.Hello Trappist. Thanks for your response at Wikipedia talk:Lua, but TBH I don't understand, as I don't know Lua at all (I have no idea what a global is). I saw someone else created this module (which is great) and want to widen its use. However, I don't know how to code it, so have just been messing around doing it by trial and error... If there's any chance you could fix it (if it's a quick fix), that would be great. Cheers, Number 5 7 22:11, 2 August 2020 (UTC)
{{
Testcase table}}
to give side-by-side renderings.local
so that its scope is limited to where it is used. Stuff will still go wrong but the wrongness is usually confined to a smaller portion of the code.as I don't know Lua at all. Not sure how wise this is as you'll need to maintain this module and handle errors and feature requests. Just throwing stuff together until it works is almost never the correct thing to do. -- Gonnym ( talk) 06:39, 3 August 2020 (UTC)
Party | Votes | % | Seats | +/– | |
---|---|---|---|---|---|
Kuomintang | 5,813,699 | 71.88 | 50 | +50 | |
Democratic Progressive Party | 2,274,586 | 28.12 | 45 | –50 | |
Valid votes | 8,088,285 | 98.57 | |||
Invalid votes | 117,160 | 1.43 | |||
Total votes | 8,205,445 | 100 | |||
Registered voters/turnout | 14,313,288 | 57.33 | |||
Source: CEC |
Could someone with Lua skills please look at this discussion:
-- Timeshifter ( talk) 10:12, 12 August 2020 (UTC)
I've done a little searching on the Wikipedia Lua resources and I don't think this is possible, but it would be great if it was so I figured I'd ask: is there any way to see a list of pages that are throwing errors when running a Lua module? Specifically, I recently revamped the {{ LDS}} template, which is used to cite to Mormon scriptures like the Book of Mormon, so that it calls a Lua module ( LDSverse). It works great, but there were a few places where people were misusing the original version of the template in a way that would just create broken external links—aka errors that were invisible to the reader on Wikipedia—but now when those bad parameters are passed to the Lua module it tends to create one of those big red Lua script error messages in the middle of Wikipedia pages. I might change how errors are handled to make the module fail more gracefully, but ideally it would be nice to find the handful of pages that are causing the errors and just fix them.
So is there by any chance a page that lists all the instances of the module causing an error? Or any way to somehow (easily) create that? If not, no worries, but I didn't want to find out there is after putting in a few hours of other work! ― biggins ( talk) 10:49, 27 August 2020 (UTC)
assert()
to catch user input errors is that it makes it look like the module is broken so editors are going to shy away from such glaring error messaging; and if they do click that message they are presented with the drop-down that is helpful to the developer but not so helpful to the common editor. Take the time to create error messaging that is useful to the common editor; categorize the errors; provide help text and a link in the error message to that help text. Save assert()
and error()
for truly broken module code.{{rcr|MZD|Yaroslavsky}}
→ Lua error: expandTemplate: template "MZD color" does not exist.I would like to mark Module:Sandbox/davidwr/example2 as {{ db-author}} but I don't think that will have any effect. What is the correct way to request speedy deletion of modules whose page name starts with Module/Sandbox/your userid/ and for which you are the only or primary author and which has never been outside of "your module-sandbox-prefix namespace"? I have blanked it.
I asked the question that way since obviously if another editor touched it, it's not equivalent to db-author, and if it's been in the "main" Module: namespace or it ever was there, others may be relying on it. davidwr/( talk)/( contribs) 20:37, 6 September 2020 (UTC)
I want to get a list of sysop in viwiki (Vietnamese Wikipedia). How can I do that by using Lua? Thank you! Alphama ( talk) 03:30, 7 September 2020 (UTC)
mw.title.new('Special:ListUsers/sysop'):getContent()
returns nil
. If you don't get an answer here, you might ask at
WP:VPT.
https://vi.wikipedia.org/w/api.php?action=query&list=allusers&augroup=sysop
. I don't know Lua well enough to know how to incorporate that into a Lua module, but worst-case you could use the API to generate a static lists of sysops, then use Lua to parse it. Form more help, see the "allusers" link under "list" in
mw:API:Query.
davidwr/(
talk)/(
contribs) 13:46, 7 September 2020 (UTC)
{{
Somebot|subst|Special:ListUsers/sysop}}
to a page might make a current list of sysops appear after it whenever Somebot runs, just as if {{subst:Special:ListUsers/sysop}} did what we might naively expect it to do.
Certes (
talk) 20:48, 9 September 2020 (UTC)I cannot edit any modules, Module:Sandbox/Gioguch/temp doesn't work. It gives you errors and does not let you publish. Can you give me some valid Lua text so I can test? Gioguch ( talk) 02:19, 22 September 2020 (UTC)
{{#invoke:Sandbox/Gioguch/temp|add|1|2}}
→ 3{{#invoke:Sandbox/Gioguch/temp|sub|1|2}}
→ -1Hello from el.wiktionary. Small wiki projects: 2-5 lonely editors, who most of the time know nothing about wikitext, lua and all that. But we find semi-finished modules, also the tasks demand some technical knowledge.
It seems that there is no wiki-support for us. I have
tried at mediawiki in vain. Our great friend
Erutuon has helped us immensely, but we cannot bother one person all the time.
The idea would be, a 'suitcase' of not complicated, friendly, copypaste modules and templates for the needs of wiktionaries, of wikipedias, of wikiwhatever. No jargon explanations, but real life examples. I have tried in a very naïve way, a suggestion of what we need at
el:wikt:User:Sarri.greek/Learn_Lua_and_wikitext. Are there any Lua writers who would like to write such a textbook? Where could I petition for a board of Lua support? Psychologically, it feels uncomfortable to seek help from outside, something boring, irritating to experts. It should have been, I think, a regular and normal thing to have an umbrella support. Thank you for listening.
Sarri.greek (
talk) 20:37, 11 October 2020 (UTC)
They? There were 2 lua people back in 2015. Gone for some years now. Never mind, forget it. Sarri.greek ( talk) 02:07, 12 October 2020 (UTC)
local export = {} ... return export
. How does this affect the way one writes the various commands? Should I correct
this structure? The variety of styles of luawriting is very confusing to rookies. Could I ask little questions like that somewhere? Something like a LuaSchool. I promise not to bother you too often.
Sarri.greek (
talk) 08:12, 12 October 2020 (UTC)
Excuse my ignorance. I have this little table: local fruits = {"apple", "melon", "orange"}
Now, I want to say: if thisparameter is one of the things belonging to local fruits, do so and so. What do I have to write?
Sarri.greek (
talk) 19:47, 12 October 2020 (UTC)
local fruits = {["apple"=true, "melon"=true, "orange"=true}
if fruitsthisparameter then <something done here> end
local fruits = {"apple", "melon", "orange"}
for _, fruit in ipairs (fruits) do
if fruit == thisparameter then <something done here> end
end
Recently i imported Module:Automatic archive navigator on bnwiki and as excepted half of module doesn't work because module needs input in en digit but its getting input in bn digit. Also this module is invoking other two module, i am not sure how to fix. I explained everything here. Please take a look. -- আফতাবুজ্জামান ( talk) 00:38, 13 October 2020 (UTC)
Hello, I reuse this module for viwiki. I would like to use both English and Vietnamese parameters:
How can use this? Thank you. Alphama ( talk) 14:40, 26 October 2020 (UTC)
//
is not valid in Lua. Did you try:
if self.args.image or self.args.hình_ảnh then
image = self.args.image or self.args.hình_ảnh,
args["hình_ảnh"]
tbl.par
which is equivalent to tbl["par"]
, which makes a string keyed ("par") value in a table (tbl) look like a property (par) of an object (tbl). Unfortunately, that bit of sugar often doesn't work when the string key is not a simple string of alphanumerics. For example tbl["a-1"]
works fine, but tbl.a-1
causes an error. As
Snaevar says, that means you can't use the object.property style of syntax when "property" contains Vietnamese characters. --
RexxS (
talk) 19:08, 26 October 2020 (UTC)table.key
is equivalent to table['key']
.ì
(U+00CC LATIN SMALL LETTER I GRAVE) be a letter in the vi.wiki locale? Is the documentation wrong? Does Scribunto impose an apparently non-Lua restriction on wikis that aren't normally written using just the ASCII character set?ì
(U+00CC LATIN SMALL LETTER I GRAVE) as part of an identifier:t = {}
t"aì" = 123
print( t"aì" )
t = {}
t.aì = 123
print( t"aì" )
t.aì
to t["aì"]
. Change the ì
to i
and it all works fine. If you want to be certain of using object.property
as an alias for object["property"]
, then you have to restrict the characters in the string "property" to [A-Za-z0-9_]. --
RexxS (
talk) 20:18, 26 October 2020 (UTC)
ì
would be alphabetic so when the Lua manual says that "any character considered alphabetic by the current locale can be used in an identifier", were I a vi.wiki editor, I would expect the Scribunto installation at vi.wiki to allow letters that are routinely used in the language. ì
is not routinely used in English so it does not surprise me that t.aì
does not work at the lua.org demo or here.The definition of letter depends on the current locale..." after 5.1. That is seen in the manuals: Lua 5.1 + Lua 5.2. Lua does things differently from many other languages but allowing non-ASCII in identifiers would be a step too far IMHO and regardless of what the Scribunto docs say, trying to use that feature (if it exists) is doomed to fail. We should probably ping Mr. Scribunto or ask at Phabricator, or just ask at the doc talk. I would say the docs should be tweaked. Johnuniq ( talk) 22:54, 26 October 2020 (UTC)
Can you check the locales of viwiki? Alphama ( talk) 13:48, 29 October 2020 (UTC)
Idea: Should we do something like multilingual parameters when we build Lua modules so that other projects can inherit these easily from English Wikipedia? In my case, I prefer to use three parameters at the same time ("image", "hình", "hình ảnh") so I need to convert the template back to the old method, without using Lua module. Alphama ( talk) 00:38, 27 October 2020 (UTC)
Picked {{ Db-multiple}} off Wikipedia:Lua/To do. See Module:Sandbox/ProcrastinatingReader/Dbm and demos at User:ProcrastinatingReader/Dbm. Biggest improvement is probably that it can now handle per-criterion arguments (rather than passing rationale to each one). I think it replicates all of the functionality of {{ Db-multiple}}. Would like to add support for custom templates of the same CSD cat, like {{ db-copypaste}}, at some point. Code is pretty messy, trying to get around some weirdities of Lua, and there's probably a neater way to do a lot of the stuff.
Usage as such:
{{#invoke:Sandbox/ProcrastinatingReader/Dbm|main|G6|rationale{{=}}leftover redirect following move of own sandbox into userspace|G7}}
Thoughts? ProcrastinatingReader ( talk) 15:52, 20 September 2020 (UTC)
Biggest improvement is probably that it can now handle per-criterion arguments (rather than passing rationale to each one).-- see sandbox demos, current CSD repeats rationale for all criteria, and in deletion summary also, even if it doesn't apply to said criteria. Also see db-meta archives ( 1, 2) re converting it into lua. ProcrastinatingReader ( talk) 16:01, 20 September 2020 (UTC)
Updated the module to annotate the code better, so hopefully it's less of a mess to follow, and simplified a few things. would someone be able to code review this? ProcrastinatingReader ( talk) 18:03, 6 November 2020 (UTC)
Could I get a code review and/or have the questions I've asked in the module? I'm learning and not entirely sure about some things. -- Izno ( talk) 17:09, 4 November 2020 (UTC)
require
(twice). It's just a function.if remaining ~= 0 then
, I would write if remaining > 0 then
for that kind of condition on the basis that you would not want to execute the following code if remaining
somehow ended up negative.frame = frame or mw.getCurrentFrame()
. That would make frame
optional.local classes = { ... }
I would put a comma on the last item. That's a personal style thing but it makes diffs much cleaner in the future when things get added or shuffled around.project = stripToNil(args['project'])
. See
Module:Age. People come up with various funky ways of handing this, the worst of which is repeating the code every time it's needed. Some use functions with names like isEmpty.for i, class in pairs(classes) do
, I recommend ipairs not pairs. For one thing, ipairs will generate the items in a defined order which doesn't matter here but is normally wanted. Also, if you ever added an option to classes like example = true
, you wouldn't want it to turn up in pairs. Finally, use _ rather than i because that variable is not used and underscore is the convention for "intentionally not used".class['count']
is Python. It's really convenient to use Lua's equivalent class.count
which works provided count
is a valid Lua identifier.if i < 9 then
to skip the inner code for 9. Using tonumber(args[i])
will give nil when someone enters a non-numeric parameter and that will give a mysterious run-time error when the addition in the next line occurs. I would either append or 0
so it doesn't crash, or or error('Need a number', 0)
to give a clue.root
rather than tostring(root)
, I believe Scribunto will apply tostring to the return value (although it turns nil into an empty string, I think) so in principle it doesn't matter. I would make it explicit.{{#invoke:dump|dumphtml|1={{Progression rainbow|20|20|100|40|30|40|10|40|310}}}}
set_message
and I see message
in
Module:Age with somewhat different implementations (though I haven't looked at the real differences). Re 'actual' i18n, there's efforts today for
Module:I18n and
Module:TNT; the latter was spawned from looking for Today solutions for
phab:T52329. (Re separate page,
loadData is of interest for those readers who don't know it for a reason to put a table of strings on a separate page instead.)root
is a table, not a string, since the example on the reference manual is to return it as a string, but I have nothing to base that on myself. :) (Maybe something to review.) I mean more for its interaction with p.main
, if relevant or interesting.tonumber(x)
returns nil whenever it can't cast x into a valid number (unlike some other less weakly-typed languages that will return 0). My advice is to always explicitly enforce typing for any function that can return nil: for example, using val = tonumber(x) or 0
will ensure that val always carries a numeric type, so won't throw errors if it is later used somewhere that insists on receiving a numeric value. My philosophy is to manage errors as gracefully as possible in production code. Editors using your code really get irate when readers see big red error messages, which should be for developers only. Cheers --
RexxS (
talk) 23:54, 5 November 2020 (UTC)Re #2 (style), I'm very sympathetic to underscores but the thing that persuaded me to jump ship was that the Scribunto Lua code (viewable from mw:Extension:Scribunto) uses it, apparently on the basis that it complies with JavaScript conventions which is the other scripting language used here. I confess to ignoring some of the other Scribunto source conventions.
Re #3 (if remaining > 0), I adopted that strategy years before seeing Lua but I'm fairly alone.
Re #4 (frame), function _main uses it twice: frame:expandTemplate{...} + return frame:extensionTag{...}. You could remove parameter frame and use local frame = mw.getCurrentFrame()
to get it, but that is pointless overhead. If you want _main to be usable by another module which might not want to bother passing frame, you would use what I wrote at #4 to make frame optional. You must use frame to call either of those functions. The reason is that the various magic words such as {{PAGENAME}} that might be used in the functions use the values from frame.
By the way, using frame:expandTemplate{...} without parentheses is using a baffling trick in Lua. Inserting parens is easy and reduces the puzzle factor for those reading the code. More importantly, using parens is consistent with other usages where they are required.
Re #5, fair enough but I will point out that redundant trailing commas have been common in many programming languages since at least the 1970s when C was introduced. They are very common in modules.
Re #7, Lua is astonishingly fast. Have a look here and its talk to see 1178 calls to {{ convert}}. The HTML source includes "Lua time usage: 1.312/10.000 seconds". Now look at the omg ugly code in Module:Convert and the two enormous modules that it uses. The speed is breathtaking. It is possible to write inefficient code that tries to do too much (mainly calling expensive functions), and those modules can hit the 10 second limit.
Re #9, given t = {a=11, b=22, 33}
, you could use t['a'] or t.a to get 11, but only t[1] can get 33 (because 1 is not a valid Lua identifier). Further, as you say, given local x = 'a'
, t[x] is the only way to get 11; t.x would give nil because t has no entry for x. Re consistency, the definition given for t works in Lua but not something like Python (using its standard syntax). Using t.a is consistent with a=11.
Re #10, a few years ago I would have agreed that having an expression in a loop was inefficient and ugly, but I've decided (particularly in Lua where the inefficiency is inconsequential) that "say what you mean" is good.
Re #11, I imagine you know that string.format is almost the same as printf. Module:TNT was what I was thinking of. We'll see how that turns out but when I last looked, the only examples had trivial code. They have listed Template:Convert as proposed for TNT but that's a bit of a dream IMHO (convert handles some unbelievably complex language weirdness that could not be put in a translation table).
Re #12, root is a table. That could be checked by putting assert(type(root) == 'table')
somewhere in the code (without saving), then previewing with a page that calls the module. To test that the assert works, change 'table' to, for example, 'string'.
Johnuniq (
talk) 04:20, 6 November 2020 (UTC)
for i, class in ipairs(classes) do
to take args instead of classes using the iterator, so still not really showing that I'm trying to fill in from args 1 through 8. There is a
sandbox and
testcases if interested. (It's somewhat academic as the current code works.) Thank you for the reviews! --
Izno (
talk) 07:47, 6 November 2020 (UTC)
for i, class in ipairs(classes) do
loop is good; it's very clear that it is getting arguments.
Johnuniq (
talk) 09:39, 6 November 2020 (UTC)This page is an archive of past discussions. Do not edit the contents of this page. If you wish to start a new discussion or revive an old one, please do so on the current talk page. |
Template ( https://ru.wikipedia.org/wiki/Шаблон:Население https://ru.wikipedia.org/wiki/Модуль:Statistical ) provides information for the users in numbers and graphs about the population. On the one hand, we have population censuses and data for different years. On the other hand, we call this data through a template simply by specifying the name of the city. But there are many thousands of cities. Working through lua-modules, we made a unique hash of the name of the city and, by a unique hash, we further searched for numbers on the population. But these are >60 tables of 3000 elements ( https://ru.wikipedia.org/wiki/Шаблон:Население/STA-061 ) for these unique hashes. lua mw.loadData results in maximum use of the amount of memory allocated for lua. The hash was placed in the templates ( https://ru.wikipedia.org/?title=Модуль:Statistical&diff=83973924&oldid=82885634 ) and searched through the switch and expandTemplate. From 4th to 7th of June, 2019, we experienced problems that appeared apparently somewhere on the server side, because before and after this period it again appears without errors. Probably the slow work of a large switch results in maximum use of the work time allocated for lua. And further template calls for the public return the red text of the error "lua limit reached". Thus, it seems that we are somewhere on the verge of the possibility of the module / templates working. Could there be a faster or more practical way to work with such a large amount of data? -- Sunpriat ( talk) 11:02, 11 June 2019 (UTC)
{{#switch:}}
parser function in
ru:Шаблон:Население/STA-061 uses Lua resources (if I am not misunderstanding), it does not. Lua resources are only used by invocations of modules. Regardless of how much time the {{#switch:}}
parser function takes, the Lua invocations are allowed to run for up to 10 seconds. —
Eru·
tuon 05:00, 12 June 2019 (UTC)This will probably be a Herculean task, but I'm hoping someone can help me with this: Can someone possibly get {{
Calendar}} "Lua-ized" via a module at
Module:Calendar? Asking since ...
something I'm trying to do ran across expensive call template include size issues. So ... I'm really hoping this can be accomplished.
Steel1943 (
talk) 00:27, 29 June 2019 (UTC)
{{
calendar}}
.
Module:Calendar widget? Continue this discussion there?{{
ISOCALENDAR}}
has form and styling vaguely similar to {{
calendar}}
and to
Module:Current events calendar so could be a candidate for the widget.I've made a start with Module:Calendar widget, Template:Calendar widget and Template:Calendar widget/styles.css. There is some testing of the module at Module talk:Calendar widget/Testing. I threw in a couple of exported functions that check for a leap year and return what day of the week a particular date is. There's virtually no inline styling in the module, but all of the tables, rows, headers and data cells have a class set that can be styled via the template's template styles. I still have to implement most of the parameters available for Template:Calendar, but I'll have another look tomorrow if I get a chance. Please feel free to hack at it if you're interested. Cheers -- RexxS ( talk) 00:26, 30 June 2019 (UTC)
2000 | |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
|
|
|
| ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
|
|
|
| ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
|
|
|
|
So I broke it. I know how it's broken but am at a loss to know why.
I had thought to use the Scribunto HTML library because it seemed to me that support for variations in styling and whatever other sorts of options that might be wanted could more easily handled by that library. I haven't used the HTML library before so my own naivete might be mostly to blame for the broken code.
As you can see the individual monthly calendars aren't top-aligned as they should be. The style is properly included but the <tr>
tag that holds it is immediately closed:
<table class="ycal"><tr class="ycalhdr"><th class="ycal" colspan="4">2000</th></tr><tr class="ycal" style="vertical-align:top"></tr><td class="ycal">
For comparison, here is the original (stretched out to make it easier to compare):
<table class="ycal"><tr class="ycalhdr"><th class="ycal" colspan="4>2000</th><tr class="ycal" style="vertical-align:top;"><td class="ycal">
I notice that the original is, I think, missing a </tr>
after the <th>...</th>
tag.
What did I do wrong? Is it bad that I have only made this change to displayyear()
and not to displaymonth()
?
The original code remains but has been commented out and there is an mw.log()
that dumps the html output to the debug console log.
— Trappist the monk ( talk) 00:51, 1 July 2019 (UTC)
<table class="ycal"><tr class="ycalhdr"><th class="ycal" colspan="4">2000</th></tr><tr class="ycal"></tr><td class="ycal">
<tr style="vertical-align:top">
apply to the enclosed <td>...</td>
tags?<table class="ycal"><tr class="ycalhdr"><th class="ycal" colspan="4">2000</th></tr><tr class="ycal"><td class="ycal">
local year_row = year_cal
makes year_row
a new object, how does
year_cal
know anything about what gets added to year_row
? This suggests to me that year_row
and year_cal
are not separate objects but are 'pointers' or 'references' to the same 'thing'. If they are 'pointers' or 'references' then that explains why everything that got added to year_row
is present at the end when return tostring (year_cal)
. But that doesn't explain why it is necessary to indirectly add the <td>...</td>
tags via year_row
.year_row
is a pointer, why is it necessary?year_cal:tag('tr') year_cal:tag('td')
just adds tags as direct children of year_cal
. Calling local year_row = year_cal:tag('tr') year_row:tag('td')
adds a tr tag to year_cal
, returns it, saves a reference to it in the local variable (because the tag
method returns a new object for the tag that was created), and using this reference adds a td tag to it rather than to year_cal
. —
Eru·
tuon 13:36, 1 July 2019 (UTC)
<td>...</td>
tags that are required for each row into :wikitext()
because that is how (as I understand it) content is meant to be added to a tag. So I hacked a function that does the necessary work to create <td>...</td>
tags and called it from year_cal:wikitext()
. It works without confusing indirection.add_td_tags()
so that it can be used more broadly than it is now. I'll think on that.For example, if module was:
local str = "Hello World!" local p = {["string"] = str}; p.hello = function(frame) return str end return p
and the template code {{#invoke:moduleName|string}}
returned Hello World!
. Or do I have to create a function if I want to achieve that? —
andrybak (
talk) 08:34, 5 July 2019 (UTC)
local
outside functions. The main concern is performance – too much global stuff slows execution down; it is better to resort to
require(modulename) in the case where heavy initialized data are desirable.
Incnis Mrsi (
talk) 09:56, 5 July 2019 (UTC)X
in {{#invoke:moduleName|X}}
has to be a function name, or whether it could be a code (such as "string") to get the code's value (such as "Hello World!"). The answer is yes it can be a code, but it's pretty ugly and involves setting a metatable on p
such that X
is interpreted at runtime. A lot less hair would be lost if the call were {{#invoke:moduleName|get|X}}
where the function get
returns the value for X. See
Module:Data for how magic metatable code can be written.
Johnuniq (
talk) 10:43, 5 July 2019 (UTC)Hello, I have few connoissances into Lua. I have (one) (or multiple words) into a given string. Example : <CDG LAX JFK> (string without the < and the >) I would need this string transformed into %22CDG%20LAX%20JFK%22 so that this being understandable by a sparql query. I have written a short code but it doesn't come the fashion I need. Any tip would be greatly appreciated. -- Bouzinac ( talk) 20:16, 23 July 2019 (UTC)
local p = {}
s=frame.args1
function p.recode(frame)
return "%22".. s:gsub(" ","%20").. "%22"
end
return p
local p = {}
function p.recode(frame)
return "%22" .. mw.uri.encode(frame.args1],"PATH") .. "%22"
end
return p
local function transform(s)
return mw.uri.encode(s:gsub("%S+", '"%1"'), "PATH")
end
function p.transform(frame)
return transform(frame.args1])
end
I'm trying to use the ParserFunctions library in lua for it's trunc() calculation, but
Help:Extension:ParserFunctions has no documentation at all how its used other than mw.ext.ParserFunctions.expr
. The most I was able to get is mw.ext.ParserFunctions.expr("trunc", value)
but that gives me the error "Lua error: Expression error: Missing operand for trunc..". Any ideas? --
Gonnym (
talk) 07:43, 24 July 2019 (UTC)
local success, result = pcall(mw.ext.ParserFunctions.expr, 'trunc 1234.5678') if success then -- result is the result else -- result is error text end
local input = 1234.5678
local truncated = math.floor(input) -- returns the same as mw.ext.ParserFunctions.expr('trunc ' .. input)
input = '1234.5678' -- works for strings, too:
truncated = math.floor(input) -- still 1234: i guess math.floor is nice enough, and calls tonumber() for you, or something. JS behave similarly
-- math.floor will throw if the parameter is not "numberable", e.g. "bla", '', or nil. you can use pcall, or test directly:
local num = tonumber(input)
if num then -- safe: in lua, 0 evaluates to true
truncated = math.floor(num)
else
-- do some error handling
end
trunc 1234.5678
or or trunc(1234.5678)
. this looks a bit bizarre (why would the editor pass something like this as a parameter?), but i guess it's possible. peace -
קיפודנחש (aka kipod) (
talk) 19:34, 24 July 2019 (UTC)
I have an array of arithmetic expressions as strings and I need to do a calculation with an x value for the relevant one, however it can't do that with an arithmetic expression as a string. I'd like to avoid needing to do this as an if/else. Any ideas? Code below:
local function main(value1, value2)
local arithmeticExpressionList = {
1 = " % 2 + 4",
4 = " / 2 % 2 + 2",
6 = " / 4 % 2 + 5",
9 = " / 8 % 2 + 5",
12 = " / 16 % 2 + 3",
14 = " / 32 % 2 + 8",
17 = " / 64 % 2 + 6"
}
local arithmeticExpression = arithmeticExpressionListvalue1
if (arithmeticExpression) then
value = value2 .. arithmeticExpression
return value
end
end
-- Gonnym ( talk) 06:51, 25 July 2019 (UTC)
value = value2 .. arithmeticExpression
should be the same result as value = 7 % 2 + 4
. % is
Modulo operation. --
Gonnym (
talk) 07:36, 25 July 2019 (UTC)local function main(value1, value2)
local arithmeticExpressionList = {
1 = function ( x ) return x % 2 + 4 end,
4 = function ( x ) return x / 2 % 2 + 2 end,
6 = function ( x ) return x / 4 % 2 + 5 end,
9 = function ( x ) return x / 8 % 2 + 5 end,
12 = function ( x ) return x / 16 % 2 + 3 end,
14 = function ( x ) return x / 32 % 2 + 8 end,
17 = function ( x ) return x / 64 % 2 + 6 end
}
local arithmeticExpression = arithmeticExpressionListvalue1
if (arithmeticExpression) then
return arithmeticExpression( value2 )
end
end
Hey, I can't see how to get an exact match. I am using [Cc]hess in a template, looking to get back only the full-word matches of " Chess " and " chess ", but I of course also get "duchess", "duchesses", "Chessie", etc. What pattern code returns only the selected characters when they are surrounded by spaces, and not part of a larger word? Thanks in advance. UnitedStatesian ( talk) 12:53, 20 August 2019 (UTC)
%f[%a]([Cc]hess)%f[%A]
%a
matches all letters, while %A
does the opposite (it matches all non-letters).
Johnuniq (
talk) 04:05, 23 August 2019 (UTC)
some of the examples on Module:InfoboxImage aren't showing any image at all, and I don't know if it's just my laptop. I tried having a look at the source but I know absolutely nothing about code so I don't know what's wrong or how to fix it... Snizzbut ( talk) 15:48, 30 September 2019 (UTC)
|suppressplaceholder=no
flag, and one uses an image that doesn't exist. I think that's correct. Do you see more than five examples without images?
Certes (
talk) 15:54, 30 September 2019 (UTC)
After mastering "hello world" my next stepping stone is code to get information for a given URL (PageSize for starters). Can some good soul turn my head in the right direction? TiA Vitosmo
Because I'm improving a fairly complex module (more than two thousand lines of code). I created this module to make easy the debugging of any other module, because the Debug console is not always useful enough.
Also I added a new chapter: Help:Lua_debugging#How_debug to explain the possibilities of debugging. Maybe it would be interesting to improve and/or correct it (since my English level is intermediate).
-- Jmarchn ( talk) 21:12, 22 October 2019 (UTC)
I'm not exactly sure what is going on, so I created a simplified example. I start with the base full table in
User:Frietjes/l which transcluded in
User:Frietjes/l1,
User:Frietjes/l2, and
User:Frietjes/l3. The problem appears in
User:Frietjes/l1 which has an efn (in the ghost references section) that does not appear in the article. I think I have isolated it to the tracking, since if I turn the tracking off, I get
User:Frietjes/l3 which doesn't have any ghost references. any idea how to get the tracking to work without showing the ghost references? feel free to make changes to
Module:Sandbox/Frietjes and/or Module:Sports table/argcheck/sandbox if you have ideas on how to fix it.
Frietjes (
talk) 17:45, 1 November 2019 (UTC)
|notracking=
) add notes for the whole table, including one for Ipswich who don't make the table due to finishing more than four places behind Arsenal.
Certes (
talk) 18:32, 1 November 2019 (UTC)
local unused = args.text_IPS
, causes the footnote to appear. It seems that the #invoke:
magic in
mw:Extension:Scribunto only evaluates each parameter when first needed, so |text_IPS={{fb...{{efn...}} }}
only produces a footnote if someone looks at the value of args.text_IPS
. Footnote f in
Wikipedia:Guide to Scribbling provides minimal evidence for this theory.
Certes (
talk) 18:01, 3 November 2019 (UTC)uses
metatables to fetch arguments from #invoke ... without using the pairs()
function
.
Certes (
talk) 18:08, 3 November 2019 (UTC)
args.foo
or args["foo"]
with an argument table output from
Module:Arguments, then pairs() isn't called on the original #invoke arguments. However, if you call pairs() on the argument table, each argument from #invoke is fetched using the next() function, which has the same effect as using pairs() on the original #invoke arguments. —
Mr. Stradivarius
♪ talk ♪ 01:40, 4 November 2019 (UTC)|text_IPS={{fb...{{efn...}} }}
evaluates as as part of the template expansion process; the module only sees the expansion of {{fb|...}}. That expansion has the side effect of creating a footnote but occurs only when Lua needs to determine the value of args.text_IPS
during
lazy evaluation. I'm not a veteran Lua coder, so please correct me if any of that is wrong!
Certes (
talk) 11:30, 4 November 2019 (UTC)
if key == "text_IPS" then return nil else return table[key] end
. Disappointingly, I can find no way to get a list of keys without evaluating their values, even with heavy
metatable manipulation.
Certes (
talk) 18:48, 4 November 2019 (UTC)
Is there a way to get the name of a variable in Lua? My use-case, I have a list of parameters passed via a template to a module and they differ by a suffix letter. I need to sum the values of all variables that end with the same letter together.
So for this local args = {arg1W = 2, arg1L = 3, arg2W = 3, arg2L = 5}
, is it possible to get the string value of the parameter names (know that args1W is "args1W")? --
Gonnym (
talk) 13:55, 20 November 2019 (UTC)
args
member of the parent frame so you can:
local parent_args=mw.getCurrentFrame():getParent().args
for param_name, param_val in pairs (parent_args) do ... end
local sums = {}
for param_name, param_val in pairs (parent_args) do
local letter = param_name:sub(-1)
sumsletter = (sumsletter or 0) + param_val
end
for k, v in pairs(sums) do
-- do something: k is the letter, v is the sum for that letter
end
-- or just use sums.W and sums.L if you know what sufix letters are going to be passed
The result of the move request was: No consensus to move the listed talk pages. While some of the participants agreed there was no harm in moving the talk pages, most felt that it made more sense to discuss changes to a module on the module's talk page. In total there were no strong opinions in either direction, so the status quo will be maintained. Primefac ( talk) 13:25, 23 November 2019 (UTC)
– Modules that are used solely to implement one template are internal stuff; the actual non-programmer-facing page is the template, so any discussion about the template should happen on the template talk page, not the module talk page. * Pppery * it has begun... 22:10, 8 November 2019 (UTC) —Relisting. Primefac ( talk) 13:14, 16 November 2019 (UTC)
If one of you Lua programmers could parametrize this for me, I'd very much appreciate it. The current hatnote seems rather derp when used in the context I've described and I'd rather not use custom hatnotes unless I have no other choice. Seppi333 ( Insert 2¢) 17:05, 30 November 2019 (UTC)
I'm trying to make a template that helps with TemplateData (basically, makes it a bit less complicated to do and has it in template form. User:Lemondoge/templatedata) Currently it only supports 3 parameters, and I am trying to figure out how to make it support infinitely many parameters. I have an unfinished module page for it ( Module:Sandbox/Lemondoge/templatedata), but I can't figure out how to make it work - already stuck on how to concatenate arguments to create JSON format. Any help? (See template page and documentation for information on the usage of the template in its current state.) {{ Lemondoge| Talk| Contributions}} 19:45, 2 December 2019 (UTC)
|label1=
, |param1=
, |description1=
, |type1=
, |status1=
; then |label2=
, ... etc.require('Module:No globals');
local getArgs = require ('Module:Arguments').getArgs;
local function function_that_does_stuff (label, param, description, ptype, status)
local result
-- wherein stuff gets done that sets result
return result
end
local function templatedata (frame)
local args=getArgs (frame)
local final_result
local i=1
while frame.args'label'..i do
local result = function_that_does_stuff (args'label'..i], args'param'..i], args'description'..i], args'type'..i], args'status'..i])
-- here do something with result to fill final_result
i = i + 1;
end
-- here do something to finish off final_result
return final_result
end
return templatedata
local final_result = "poof"
), the template will do nothing, regardless of parameters. Current code is:
require('Module:No globals');
local getArgs = require ('Module:Arguments').getArgs;
local p = {}
local function function_that_does_stuff (label, param, description, ptype, status)
local result
result = '"'..param..'": { "label": '..label..'", "description": "'..description..'", "type": "'..ptype..'", "required": '..status..' },'
return result.."poof"
end
function p.templatedata (frame)
local args=getArgs (frame)
local final_result
local i=1
while frame.args'label'..i do
local result = function_that_does_stuff (args'label'..i], args'param'..i], args'description'..i], args'type'..i], args'status'..i])
final_result = final_result..result
i = i + 1;
end
return final_result
end
return p
Hi, I just continue with Lemondoges request - which does not bear an answer to my problem:
But at the moment I am not able to perform a repetitive frame:expandTemplate{ title = title, args = }
where the argument[s] are one after the other the values from a loop;
Lua seems to allow only one frame:expandTemplate{}
as the only one return value?
When that is the concept of Lua, this restriction should be expanded, because there are numerous templates having problems with long parameter lists! Poor code constructions like {{#if:{{{1|}}}|... until e.g. {{#if:{{{33|}}}|... will fail as soon as there are 34 parameters to handle. A loop in Lua can serve any uncountable number of parameters, when the repetitive transclusion is possible.
sarang♥
사랑 16:40, 14 January 2020 (UTC)
{{{1}}}
... {{{n}}}
then you might write something like this (untested and presuming that you have extracted an args table from the appropriate frame):
local out = {}
for i, v in ipairs (args) do
table.insert (out, frame:expandTemplate{ title = title, args = v })
end
return table.concat (out)
Another thing I cannot find information about: sure there must be an access to the system variables (of course it can be passed by a template, but how con I get it directly by the Lua code); how can I get e.g. environment parameters like the {{PAGENAME}} where the code is executed? sarang♥ 사랑 12:25, 19 January 2020 (UTC)
mw.title.getCurrentTitle().text
do what you want? If you are looking for the name of the module then frame:getTitle()
. Have you looked in
mw:Extension:Scribunto/Lua reference manual?Please see Template talk:Trim quotes#Wikimarkup interference. Trying to get Lua to do this gives me a headache, though I could do it easily in bash or Perl or whatnot. Lua just hasn't sunk in yet. — SMcCandlish ☏ ¢ 😼 21:35, 30 January 2020 (UTC)
I just created Module:Is_stub for merging {{ uncategorized stub}}. It detects if a page is tagged with a stub tag or not with a very high accuracy. Could someone please tell me either point me to the existing template for this purpose or tell me why this is a bad idea. I won't believe that this is the first time someone have thought of this. ‑‑ Trialpears ( talk) 21:54, 30 January 2020 (UTC)
{{#if:{{#invoke:String|match|{{#invoke:Page|getContent|{{FULLPAGENAME}}|as=raw}}|stub|ignore_errors=1}}|yes|no}}
does the exact same thing without creating more module bloat.
* Pppery *
it has begun... 00:17, 31 January 2020 (UTC)
You are invited to join the discussion at Wikipedia:Templates for discussion/Log/2020 February 13#Module:HelloWorld. * Pppery * it has begun... 22:28, 13 February 2020 (UTC)
You are invited to join the discussion at Wikipedia:Help_desk#Why_do_so_many_commonly-used_templates_use_MODULES?_When_they_don't_need_to?. * Pppery * it has begun... 01:15, 15 February 2020 (UTC)
Hi All,
Please have a look at my proposal and contribute with your opinions: Wikipedia:Village_pump_(proposals)#Connecting_Wikipedia_articles_to_reliable_sources_through_new_template
Thanks, Adam Harangozó ( talk) 14:14, 23 February 2020 (UTC)
Hi! Is there a way to get the list of pages in a category within a Lua module? I checked the Lua reference manual carefully, thought about it and tried a few things, but no luck, so before giving up I thought about asking here. Thanks! Sophivorus ( talk) 19:15, 23 March 2020 (UTC)
<math>...</math>
tags from the math strip marker using mw.text.unstripNoWiki()
. That was, and still is important to me because the content of <math>...</math>
tags is rendered as images. cs1|2 creates metadata for use by
Zotero and other reference management software. But, the metadata doesn't accept the transient images that mediawiki uses to render the equation. For the metadata, cs1|2 used to get the content of the math strip marker and extracted the original source equation from the <math>...</math>
tags for use in the metadata. But, mediawiki took away that ability so now, metadata for article titles with equations use MATH RENDER ERROR text in place of the equation (better that than as percent encoded version of the strip marker).Per this discussion at the VPT (start reading at "related idea"), we'd like to have a module that can take as input a given page and return the text from the {{ Nutshell}} on that page if one exists (and return "null" or something if the page doesn't have a nutshell). Would that be possible to create without too much effort? {{u| Sdkb}} talk 21:14, 4 April 2020 (UTC)
{{
nutshell}}
template in the target page, I think that can be done. But shortcuts often link to sections that don't have {{nutshell}}
and for for those that do the search has to be constrained to that section and you have to look for {{nutshell}}
and all of its redirects:
{{
Essay in a nutshell}}
{{
Guideline in a nutshell}}
{{
Guideline one liner}}
{{
In a nutshell}}
{{
Inanutshell}}
{{
Naming convention in a nutshell}}
{{
Nutshell2}}
{{
Policy in a nutshell}}
{{
Policy proposal in a nutshell}}
{{
Proposal in a nutshell}}
Improve pages wherever you can, and do not worry about leaving them imperfect. Preserve the value that others add, even if they "did it wrong" (try to fix it rather than [[WP:Deletion policy|delete it]]).
[[WP:EP|<span title="Improve pages wherever you can, and do not worry about leaving them imperfect. Preserve the value that others add, even if they 'did it wrong' (try to fix it rather than [[WP:Deletion policy|delete it]]).">WP:EP</span>]]
{{
nutshell}}
redirect patterns with whitespace; works well with ipairs()
:
local redirects_nutshell_patterns = {
'{{%s*[Nn]utshell%s*|',
'{{%s*[Ee]ssay in a nutshell%s*|',
'{{%s*[Gg]uideline in a nutshell%s*|',
'{{%s*[Gg]uideline one liner%s*|',
'{{%s*[Ii]n a nutshell%s*|',
'{{%s*[Ii]nanutshell%s*|',
'{{%s*[Nn]aming convention in a nutshell%s*|',
'{{%s*[Nn]utshell2%s*|',
'{{%s*[Pp]olicy in a nutshell%s*|',
'{{%s*[Pp]olicy proposal in a nutshell%s*|',
'{{%s*[Pp]roposal in a nutshell%s*|',
}
local function wikilink_strip (template)
for wikilink in template:gmatch ('%[%b[]%]') do -- get a wikilink
if wikilink then
template = template:gsub ('%[%b[]%]', '__57r1P__', 1); -- install a marker
if wikilink:match ('%[%[.-|(.-)%]%]') then
wikilink = wikilink:match ('%[%[.-|(.-)%]%]'); -- extract label from complex [[link|label]] wikilink
else
wikilink = wikilink:match ('%[%[(.-)%]%]'); -- extract link from simple [[link]] wikilinks
end
wikilink = escape_lua_magic_chars (wikilink); -- in case there are lua magic characters in wikilink
template = template:gsub ('__57r1P__', wikilink, 1); -- replace the marker with the appropriate text
end
end
return template;
end
if wikilink then
may not be necessary. I think it is a left-over artifact from an earlier version of the code that did not work.|title=
? Ignore?find()
to find a particular nutshell pattern then, with the start position returned from find()
, use match ('%b{}', start)
to get the whole template.ustring
functions?{{nutshell}}
; it is not.Find a better module name.I'm not passionate about the name. You are welcome to give it another one.
Is it really necessary to use the ustring
functions?
Not anymore :)escape_lua_magic_chars()
Where is this defined, and how important is it?--[[--------------------------< E S C A P E _ L U A _ M A G I C _ C H A R S >----------------------------------
Returns a string where all of lua's magic characters have been escaped. This is important because functions like
string.gsub() treat their pattern and replace strings as patterns, not literal strings.
]]
local function escape_lua_magic_chars (argument)
argument = argument:gsub("%%", "%%%%"); -- replace % with %%
argument = argument:gsub("([%^%$%(%)%.%[%]%*%+%-%?])", "%%%1"); -- replace all other lua magic pattern characters
return argument;
end
wikilink_strip()
because something that was being stripped had a percent-encoded space (%20
) in it that caused lua to choke because it saw that as a capture reference that it had not captured. You may never encounter that problem. I don't remember why I separated the %
escape from the rest of the lua magic characters. I've had no reason to change it because it has been working since I don't remember when.{{
WP|BOLD}}
. But maybe the WP should just be a shortcut and the template itself should be given a better name.
Pppery, I'm having some trouble getting {{
Template parameter value}} to work correctly. Do you or anyone else know what I'm doing wrong at
User:Guywan/Test2? {{u|
Sdkb}}
talk 22:26, 7 April 2020 (UTC)
{{template parameter value|{{#invoke:Redirect|main|WP:BOLD}}|nutshell|1|1|1|1}}
{{template parameter value|{{#invoke:Redirect|main|WP:BOLD}}|Nutshell|1|1|1|1}}
|title=
.{{#invoke:WP | main | SIG }}
→
WP:SIG[[File:OOjs UI icon signature-ltr.svg|22px]]
(
) renders in the tooltip as 22px; what to do about that?{{
nutshell}}
template.@ Trappist the monk: Re image, it seems very rare for an image to be in a nutshell, so I'd say no. The alt text might occasionally work, but it's just as (if not more) likely to be missing or incomplete, which would just add to the confusion. The current solution of "[IMAGE]" at least alerts the reader that there's an image there and that they might just want to click through.
Re stubs, it seems perfectly possible that a stub would have a nutshell, so I don't see why we'd want to exclude them from the template. Maybe figure out the WP:FENCE aspect, but if there's nothing technical making it necessary, just get rid of it.
Re other namespace abbreviations,
Template:MOS, unlike
Template:WP, is taken, so it'd be hard to allow {{MOS|LEAD}}
, but
WP:LEAD works fine, and goes to the same place.
And I'm glad to see the page titles now being included! (Thanks for coding that!) I notice that it can get a bit confusing for some, as in WP:BITE seems to be talking about biting newcomers in a nutshell (lol) with the current Wikipedia:Please do not bite the newcomers in a nutshell: Do not be... Adding quotes around the title could fix that. We could also use a period or line break to make it clearer that the link goes to the page. Together with those changes, we'd have something like "Wikipedia:Please do not bite the newcomers". In a nutshell: Do not be... I'm also on the fence about whether to we should take out the "Wikipedia:" — do you think it adds enough to be worth including?
Oh, and one thing showing up in WP:NPOV and a few other test cases is that italics and bolding aren't being reflected. Do Wikipedia tooltips have the technical capability to handle formatting like that? (If so, it might be nice to bold the article title to help it stand out a bit.) {{u| Sdkb}} talk 19:45, 12 April 2020 (UTC)
{{
nutshell}}
. Just to prove that the stub search portion of that isn't broken,
this search finds about 2500 stub templates. Given these results, I'm going to delete that snippet of code. If it turns out that there is a reason for it being there, the code is in the history of the module so it can be dredged up and restored.{{WP|MOS:LEAD}}
) that would render as
MOS:LEAD (with the tool tip and dotted underlining). It is my understanding that MOS shortcuts are preferred for the manual of style. Maybe I'll hack something into this code to see how that would work.<b>...</b>
around the article title portion of the tooltip. Not surprisingly, html tags inside a title attribute inside a <span>
confused MediaWiki so the enclosing <span>...</span>
rendered as linked plain text (but the title was bold). Right now, we do nothing with the bold and italic markup so where it exists in the {{nutshell}}
text, it shows up as raw markup in the tooltip. Leave it because we all know what it means, or strip it?{{WP|Help:CS1}}
→
Help:CS1{{WP|Project:LEAD}}
→
Project:LEAD{{WP|mos:MED}}
→
MOS:MEDmain
function. I unified namespaces
and pseudo_namespaces
so we only have to lookup in one table. Namespace input like h
, H
, pRoJeCt
, and mOs
are 'normalised' to Help
, Project
, and MOS
. —
guywan (
talk •
contribs) 14:27, 14 April 2020 (UTC)
<namespace>:<title>
shortcuts into another namespace. Namespace names and aliases are case insensitive and separated from the shortcut's article title with the colon. The title portion must obey the same case-sensitivity rules as any other page title:
[[wp:MED]]
→
wp:BOLD works; nominal redirect (page ID: 1502969)[[wp:mED]]
→
wp:bOLD works; same redirect as above (page ID: 1502969) because of the first-character case-insensitivity rule[[wp:med]]
→
wp:bold works; another redirect from WP:Bold (page ID: 1502965)[[wp:mEd]]
→
wp:bOLd does not work; no redirectDoes anyone know how to look up " globalSiteId' of the wiki the code is running on? So "enwiki" on English wikipedia, "commonswiki" for Commons, etc. I am updating c:Module:Interwiki and would like to ensure that the module will not add link to itself, even if copied to other wiki. -- Jarekt ( talk) 19:39, 22 April 2020 (UTC)
{{#invoke:WikidataIB |globalSiteID}}
→ enwikimw.wikibase.getGlobalSiteId()
. Cheers --
RexxS (
talk) 19:58, 22 April 2020 (UTC)
Do really http://lua-users.org/wiki/ a resource included the Lua list here, does not use MediaWiki? :-? BoldLuis ( talk) 09:15, 18 May 2020 (UTC)
Is there a way in Lua, magic words or regular template syntax to get the Display title value of a page (which doesn't involve reading the page content)? Wondering since its a value shown in the Page information of a page. -- Gonnym ( talk) 07:56, 20 May 2020 (UTC)
{{FULLPAGENAME}}
to cause problems for your application?{{#invoke: WikidataIB |getSiteLink |qid=Q10044351}}
to get 'ICarly season 6'. Leaving out the |qid=
will use the connected article for the page: {{#invoke: WikidataIB |getSiteLink}}
→ .Display titleis the desired result then the wikidata won't work because the displayed title is: iCarly (season 6) – italics and first character lowercase. Even if it were possible to get the displayed title, how would it be returned?
''iCarly'' (season 6)
<i>iCarly</i> (season 6)
Please could someone help to create radio button functionality for switching between historical maps?
Currently Module:Location map gives the ability for a reader to switch between contemporary map views using radio buttons (see example on the right). For historical maps, comparing what an area looks like today to how it looked historically, there is no template or module which can do the same. It would benefit articles about historical settlements which look very different today (for example Tenochtitlan in Mexico City, Cahokia in St. Clair County, Illinois, Londinium in London and Lutetia in Paris). The best I have been able to come up with is the gif on the right, but it has been fairly derided as overly "distracting".
Would it be possible to extract the relevant code from Module:Location map into a new "Module:Image select" or similar? It doesn't need any of the other functionality (e.g. coordinates, labels) as it can all be covered by the buttons and captions.
Onceinawhile ( talk) 09:21, 24 June 2020 (UTC)
Right now Module:SimpleDebug is transcluded into Cynthia Brewer. My assertion is that we should avoid transcluding testing modules. Can someone see if they can remove that use from there? -- Izno ( talk) 15:01, 20 July 2020 (UTC)
require
in
Module:TNTTools because it did not appear to be used in that module.Throughout the motorsport we use mostly similar color schemes and tables. And in the popular motorsport we use and update the same data but we update it on the different pages doing more edits than we actually need. I made an intermediate solution but it is a bit clumsy. All motorsport community will be pleased if you help us to made a module for the motorsport tables (their common look here. P.S. Also we had two slightly different tables , but probably they also could have connection and receive updates from the same source template/module. The example of the cells from such tables below: {{F1R2020|HAM|HUN}}
1PF |
HUN 1 |
P.S.S. The issue with Module:Sports rbr table is that we can't add Template:F1 race position or bold/italics. Also we need a possibility to add extra column for positions and numbers (in the case of the teams' standings). Corvus tristis ( talk) 03:39, 26 July 2020 (UTC)
Hello. Is anyone able to help me sort out
Module:Election results/sandbox? I can't work out what I've done wrong to make {{
Election results/testcases}} go wrong for the latter two tables. I suspect it's something to do with the second elseif cand then
section. There are a few other functions I'd also like to add to it, which I was planning to do by trial and error, but if anyone has a bit of time to assist, I'd be most appreciative. Cheers,
Number
5
7 21:36, 2 August 2020 (UTC)
cand
and sc
don't appear to be initialized by your code (Lua inits them to nil) and both are globals. Generally not a good idea to have globals if they can be avoided. Consider adding require('Module:No globals')
at the top of your sandbox. It will help find (mis)used globals.Hello Trappist. Thanks for your response at Wikipedia talk:Lua, but TBH I don't understand, as I don't know Lua at all (I have no idea what a global is). I saw someone else created this module (which is great) and want to widen its use. However, I don't know how to code it, so have just been messing around doing it by trial and error... If there's any chance you could fix it (if it's a quick fix), that would be great. Cheers, Number 5 7 22:11, 2 August 2020 (UTC)
{{
Testcase table}}
to give side-by-side renderings.local
so that its scope is limited to where it is used. Stuff will still go wrong but the wrongness is usually confined to a smaller portion of the code.as I don't know Lua at all. Not sure how wise this is as you'll need to maintain this module and handle errors and feature requests. Just throwing stuff together until it works is almost never the correct thing to do. -- Gonnym ( talk) 06:39, 3 August 2020 (UTC)
Party | Votes | % | Seats | +/– | |
---|---|---|---|---|---|
Kuomintang | 5,813,699 | 71.88 | 50 | +50 | |
Democratic Progressive Party | 2,274,586 | 28.12 | 45 | –50 | |
Valid votes | 8,088,285 | 98.57 | |||
Invalid votes | 117,160 | 1.43 | |||
Total votes | 8,205,445 | 100 | |||
Registered voters/turnout | 14,313,288 | 57.33 | |||
Source: CEC |
Could someone with Lua skills please look at this discussion:
-- Timeshifter ( talk) 10:12, 12 August 2020 (UTC)
I've done a little searching on the Wikipedia Lua resources and I don't think this is possible, but it would be great if it was so I figured I'd ask: is there any way to see a list of pages that are throwing errors when running a Lua module? Specifically, I recently revamped the {{ LDS}} template, which is used to cite to Mormon scriptures like the Book of Mormon, so that it calls a Lua module ( LDSverse). It works great, but there were a few places where people were misusing the original version of the template in a way that would just create broken external links—aka errors that were invisible to the reader on Wikipedia—but now when those bad parameters are passed to the Lua module it tends to create one of those big red Lua script error messages in the middle of Wikipedia pages. I might change how errors are handled to make the module fail more gracefully, but ideally it would be nice to find the handful of pages that are causing the errors and just fix them.
So is there by any chance a page that lists all the instances of the module causing an error? Or any way to somehow (easily) create that? If not, no worries, but I didn't want to find out there is after putting in a few hours of other work! ― biggins ( talk) 10:49, 27 August 2020 (UTC)
assert()
to catch user input errors is that it makes it look like the module is broken so editors are going to shy away from such glaring error messaging; and if they do click that message they are presented with the drop-down that is helpful to the developer but not so helpful to the common editor. Take the time to create error messaging that is useful to the common editor; categorize the errors; provide help text and a link in the error message to that help text. Save assert()
and error()
for truly broken module code.{{rcr|MZD|Yaroslavsky}}
→ Lua error: expandTemplate: template "MZD color" does not exist.I would like to mark Module:Sandbox/davidwr/example2 as {{ db-author}} but I don't think that will have any effect. What is the correct way to request speedy deletion of modules whose page name starts with Module/Sandbox/your userid/ and for which you are the only or primary author and which has never been outside of "your module-sandbox-prefix namespace"? I have blanked it.
I asked the question that way since obviously if another editor touched it, it's not equivalent to db-author, and if it's been in the "main" Module: namespace or it ever was there, others may be relying on it. davidwr/( talk)/( contribs) 20:37, 6 September 2020 (UTC)
I want to get a list of sysop in viwiki (Vietnamese Wikipedia). How can I do that by using Lua? Thank you! Alphama ( talk) 03:30, 7 September 2020 (UTC)
mw.title.new('Special:ListUsers/sysop'):getContent()
returns nil
. If you don't get an answer here, you might ask at
WP:VPT.
https://vi.wikipedia.org/w/api.php?action=query&list=allusers&augroup=sysop
. I don't know Lua well enough to know how to incorporate that into a Lua module, but worst-case you could use the API to generate a static lists of sysops, then use Lua to parse it. Form more help, see the "allusers" link under "list" in
mw:API:Query.
davidwr/(
talk)/(
contribs) 13:46, 7 September 2020 (UTC)
{{
Somebot|subst|Special:ListUsers/sysop}}
to a page might make a current list of sysops appear after it whenever Somebot runs, just as if {{subst:Special:ListUsers/sysop}} did what we might naively expect it to do.
Certes (
talk) 20:48, 9 September 2020 (UTC)I cannot edit any modules, Module:Sandbox/Gioguch/temp doesn't work. It gives you errors and does not let you publish. Can you give me some valid Lua text so I can test? Gioguch ( talk) 02:19, 22 September 2020 (UTC)
{{#invoke:Sandbox/Gioguch/temp|add|1|2}}
→ 3{{#invoke:Sandbox/Gioguch/temp|sub|1|2}}
→ -1Hello from el.wiktionary. Small wiki projects: 2-5 lonely editors, who most of the time know nothing about wikitext, lua and all that. But we find semi-finished modules, also the tasks demand some technical knowledge.
It seems that there is no wiki-support for us. I have
tried at mediawiki in vain. Our great friend
Erutuon has helped us immensely, but we cannot bother one person all the time.
The idea would be, a 'suitcase' of not complicated, friendly, copypaste modules and templates for the needs of wiktionaries, of wikipedias, of wikiwhatever. No jargon explanations, but real life examples. I have tried in a very naïve way, a suggestion of what we need at
el:wikt:User:Sarri.greek/Learn_Lua_and_wikitext. Are there any Lua writers who would like to write such a textbook? Where could I petition for a board of Lua support? Psychologically, it feels uncomfortable to seek help from outside, something boring, irritating to experts. It should have been, I think, a regular and normal thing to have an umbrella support. Thank you for listening.
Sarri.greek (
talk) 20:37, 11 October 2020 (UTC)
They? There were 2 lua people back in 2015. Gone for some years now. Never mind, forget it. Sarri.greek ( talk) 02:07, 12 October 2020 (UTC)
local export = {} ... return export
. How does this affect the way one writes the various commands? Should I correct
this structure? The variety of styles of luawriting is very confusing to rookies. Could I ask little questions like that somewhere? Something like a LuaSchool. I promise not to bother you too often.
Sarri.greek (
talk) 08:12, 12 October 2020 (UTC)
Excuse my ignorance. I have this little table: local fruits = {"apple", "melon", "orange"}
Now, I want to say: if thisparameter is one of the things belonging to local fruits, do so and so. What do I have to write?
Sarri.greek (
talk) 19:47, 12 October 2020 (UTC)
local fruits = {["apple"=true, "melon"=true, "orange"=true}
if fruitsthisparameter then <something done here> end
local fruits = {"apple", "melon", "orange"}
for _, fruit in ipairs (fruits) do
if fruit == thisparameter then <something done here> end
end
Recently i imported Module:Automatic archive navigator on bnwiki and as excepted half of module doesn't work because module needs input in en digit but its getting input in bn digit. Also this module is invoking other two module, i am not sure how to fix. I explained everything here. Please take a look. -- আফতাবুজ্জামান ( talk) 00:38, 13 October 2020 (UTC)
Hello, I reuse this module for viwiki. I would like to use both English and Vietnamese parameters:
How can use this? Thank you. Alphama ( talk) 14:40, 26 October 2020 (UTC)
//
is not valid in Lua. Did you try:
if self.args.image or self.args.hình_ảnh then
image = self.args.image or self.args.hình_ảnh,
args["hình_ảnh"]
tbl.par
which is equivalent to tbl["par"]
, which makes a string keyed ("par") value in a table (tbl) look like a property (par) of an object (tbl). Unfortunately, that bit of sugar often doesn't work when the string key is not a simple string of alphanumerics. For example tbl["a-1"]
works fine, but tbl.a-1
causes an error. As
Snaevar says, that means you can't use the object.property style of syntax when "property" contains Vietnamese characters. --
RexxS (
talk) 19:08, 26 October 2020 (UTC)table.key
is equivalent to table['key']
.ì
(U+00CC LATIN SMALL LETTER I GRAVE) be a letter in the vi.wiki locale? Is the documentation wrong? Does Scribunto impose an apparently non-Lua restriction on wikis that aren't normally written using just the ASCII character set?ì
(U+00CC LATIN SMALL LETTER I GRAVE) as part of an identifier:t = {}
t"aì" = 123
print( t"aì" )
t = {}
t.aì = 123
print( t"aì" )
t.aì
to t["aì"]
. Change the ì
to i
and it all works fine. If you want to be certain of using object.property
as an alias for object["property"]
, then you have to restrict the characters in the string "property" to [A-Za-z0-9_]. --
RexxS (
talk) 20:18, 26 October 2020 (UTC)
ì
would be alphabetic so when the Lua manual says that "any character considered alphabetic by the current locale can be used in an identifier", were I a vi.wiki editor, I would expect the Scribunto installation at vi.wiki to allow letters that are routinely used in the language. ì
is not routinely used in English so it does not surprise me that t.aì
does not work at the lua.org demo or here.The definition of letter depends on the current locale..." after 5.1. That is seen in the manuals: Lua 5.1 + Lua 5.2. Lua does things differently from many other languages but allowing non-ASCII in identifiers would be a step too far IMHO and regardless of what the Scribunto docs say, trying to use that feature (if it exists) is doomed to fail. We should probably ping Mr. Scribunto or ask at Phabricator, or just ask at the doc talk. I would say the docs should be tweaked. Johnuniq ( talk) 22:54, 26 October 2020 (UTC)
Can you check the locales of viwiki? Alphama ( talk) 13:48, 29 October 2020 (UTC)
Idea: Should we do something like multilingual parameters when we build Lua modules so that other projects can inherit these easily from English Wikipedia? In my case, I prefer to use three parameters at the same time ("image", "hình", "hình ảnh") so I need to convert the template back to the old method, without using Lua module. Alphama ( talk) 00:38, 27 October 2020 (UTC)
Picked {{ Db-multiple}} off Wikipedia:Lua/To do. See Module:Sandbox/ProcrastinatingReader/Dbm and demos at User:ProcrastinatingReader/Dbm. Biggest improvement is probably that it can now handle per-criterion arguments (rather than passing rationale to each one). I think it replicates all of the functionality of {{ Db-multiple}}. Would like to add support for custom templates of the same CSD cat, like {{ db-copypaste}}, at some point. Code is pretty messy, trying to get around some weirdities of Lua, and there's probably a neater way to do a lot of the stuff.
Usage as such:
{{#invoke:Sandbox/ProcrastinatingReader/Dbm|main|G6|rationale{{=}}leftover redirect following move of own sandbox into userspace|G7}}
Thoughts? ProcrastinatingReader ( talk) 15:52, 20 September 2020 (UTC)
Biggest improvement is probably that it can now handle per-criterion arguments (rather than passing rationale to each one).-- see sandbox demos, current CSD repeats rationale for all criteria, and in deletion summary also, even if it doesn't apply to said criteria. Also see db-meta archives ( 1, 2) re converting it into lua. ProcrastinatingReader ( talk) 16:01, 20 September 2020 (UTC)
Updated the module to annotate the code better, so hopefully it's less of a mess to follow, and simplified a few things. would someone be able to code review this? ProcrastinatingReader ( talk) 18:03, 6 November 2020 (UTC)
Could I get a code review and/or have the questions I've asked in the module? I'm learning and not entirely sure about some things. -- Izno ( talk) 17:09, 4 November 2020 (UTC)
require
(twice). It's just a function.if remaining ~= 0 then
, I would write if remaining > 0 then
for that kind of condition on the basis that you would not want to execute the following code if remaining
somehow ended up negative.frame = frame or mw.getCurrentFrame()
. That would make frame
optional.local classes = { ... }
I would put a comma on the last item. That's a personal style thing but it makes diffs much cleaner in the future when things get added or shuffled around.project = stripToNil(args['project'])
. See
Module:Age. People come up with various funky ways of handing this, the worst of which is repeating the code every time it's needed. Some use functions with names like isEmpty.for i, class in pairs(classes) do
, I recommend ipairs not pairs. For one thing, ipairs will generate the items in a defined order which doesn't matter here but is normally wanted. Also, if you ever added an option to classes like example = true
, you wouldn't want it to turn up in pairs. Finally, use _ rather than i because that variable is not used and underscore is the convention for "intentionally not used".class['count']
is Python. It's really convenient to use Lua's equivalent class.count
which works provided count
is a valid Lua identifier.if i < 9 then
to skip the inner code for 9. Using tonumber(args[i])
will give nil when someone enters a non-numeric parameter and that will give a mysterious run-time error when the addition in the next line occurs. I would either append or 0
so it doesn't crash, or or error('Need a number', 0)
to give a clue.root
rather than tostring(root)
, I believe Scribunto will apply tostring to the return value (although it turns nil into an empty string, I think) so in principle it doesn't matter. I would make it explicit.{{#invoke:dump|dumphtml|1={{Progression rainbow|20|20|100|40|30|40|10|40|310}}}}
set_message
and I see message
in
Module:Age with somewhat different implementations (though I haven't looked at the real differences). Re 'actual' i18n, there's efforts today for
Module:I18n and
Module:TNT; the latter was spawned from looking for Today solutions for
phab:T52329. (Re separate page,
loadData is of interest for those readers who don't know it for a reason to put a table of strings on a separate page instead.)root
is a table, not a string, since the example on the reference manual is to return it as a string, but I have nothing to base that on myself. :) (Maybe something to review.) I mean more for its interaction with p.main
, if relevant or interesting.tonumber(x)
returns nil whenever it can't cast x into a valid number (unlike some other less weakly-typed languages that will return 0). My advice is to always explicitly enforce typing for any function that can return nil: for example, using val = tonumber(x) or 0
will ensure that val always carries a numeric type, so won't throw errors if it is later used somewhere that insists on receiving a numeric value. My philosophy is to manage errors as gracefully as possible in production code. Editors using your code really get irate when readers see big red error messages, which should be for developers only. Cheers --
RexxS (
talk) 23:54, 5 November 2020 (UTC)Re #2 (style), I'm very sympathetic to underscores but the thing that persuaded me to jump ship was that the Scribunto Lua code (viewable from mw:Extension:Scribunto) uses it, apparently on the basis that it complies with JavaScript conventions which is the other scripting language used here. I confess to ignoring some of the other Scribunto source conventions.
Re #3 (if remaining > 0), I adopted that strategy years before seeing Lua but I'm fairly alone.
Re #4 (frame), function _main uses it twice: frame:expandTemplate{...} + return frame:extensionTag{...}. You could remove parameter frame and use local frame = mw.getCurrentFrame()
to get it, but that is pointless overhead. If you want _main to be usable by another module which might not want to bother passing frame, you would use what I wrote at #4 to make frame optional. You must use frame to call either of those functions. The reason is that the various magic words such as {{PAGENAME}} that might be used in the functions use the values from frame.
By the way, using frame:expandTemplate{...} without parentheses is using a baffling trick in Lua. Inserting parens is easy and reduces the puzzle factor for those reading the code. More importantly, using parens is consistent with other usages where they are required.
Re #5, fair enough but I will point out that redundant trailing commas have been common in many programming languages since at least the 1970s when C was introduced. They are very common in modules.
Re #7, Lua is astonishingly fast. Have a look here and its talk to see 1178 calls to {{ convert}}. The HTML source includes "Lua time usage: 1.312/10.000 seconds". Now look at the omg ugly code in Module:Convert and the two enormous modules that it uses. The speed is breathtaking. It is possible to write inefficient code that tries to do too much (mainly calling expensive functions), and those modules can hit the 10 second limit.
Re #9, given t = {a=11, b=22, 33}
, you could use t['a'] or t.a to get 11, but only t[1] can get 33 (because 1 is not a valid Lua identifier). Further, as you say, given local x = 'a'
, t[x] is the only way to get 11; t.x would give nil because t has no entry for x. Re consistency, the definition given for t works in Lua but not something like Python (using its standard syntax). Using t.a is consistent with a=11.
Re #10, a few years ago I would have agreed that having an expression in a loop was inefficient and ugly, but I've decided (particularly in Lua where the inefficiency is inconsequential) that "say what you mean" is good.
Re #11, I imagine you know that string.format is almost the same as printf. Module:TNT was what I was thinking of. We'll see how that turns out but when I last looked, the only examples had trivial code. They have listed Template:Convert as proposed for TNT but that's a bit of a dream IMHO (convert handles some unbelievably complex language weirdness that could not be put in a translation table).
Re #12, root is a table. That could be checked by putting assert(type(root) == 'table')
somewhere in the code (without saving), then previewing with a page that calls the module. To test that the assert works, change 'table' to, for example, 'string'.
Johnuniq (
talk) 04:20, 6 November 2020 (UTC)
for i, class in ipairs(classes) do
to take args instead of classes using the iterator, so still not really showing that I'm trying to fill in from args 1 through 8. There is a
sandbox and
testcases if interested. (It's somewhat academic as the current code works.) Thank you for the reviews! --
Izno (
talk) 07:47, 6 November 2020 (UTC)
for i, class in ipairs(classes) do
loop is good; it's very clear that it is getting arguments.
Johnuniq (
talk) 09:39, 6 November 2020 (UTC)