Wikipedia talk:Lua

Page contents not supported in other languages.
From Wikipedia, the free encyclopedia

This is an old revision of this page, as edited by Guywan (talk | contribs) at 22:19, 5 April 2020 (→‎Script to fetch the nutshell text of a given page). The present address (URL) is a permanent link to this revision, which may differ significantly from the current revision.

Looped args with TemplateData template

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)[reply]

First, in the template, enumerate parameters with digits not with text; if you don't, parameter names will get really ugly really fast. Do not mix positional parameters with named parameters; that will simply cause you headaches and confusion down the road so: |label1=, |param1=, |description1=, |type1=, |status1=; then |label2=, ... etc.
You can create a loop that calls a function by doing something like:
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
caveat lector: the above is just hacked from the top of my head; not tested, probably has bugs, but should serve as a starting place.
Trappist the monk (talk) 20:19, 2 December 2019 (UTC)[reply]
As far as what I'm doing goes, this does not seem to function properly. If I leave this unmodified for debug and just invoke the function, it gives this: "Script error: The module returned a function value. It is supposed to return an export table." Otherwise, final_result seems to just not be written to at all - unless I just define it as a string (e.g. 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
{​{Lemondoge|Talk|Contributions}} 22:54, 2 December 2019 (UTC)[reply]
Update: hold up it gives you a sort of VisualEditor thingamajig for doing TemplateData on the top-left of a template documentation page when you're editing it - apparently this template thing is basically just pre-deprecated and useless. abort mission {​{Lemondoge|Talk|Contributions}} 23:10, 2 December 2019 (UTC)[reply]

Again looped args

Hi, I just continue with Lemondoges request - which does not bear an answer to my problem:

  1. a template gets an unknown, possibly large amount of parameters. For each parameter the same action is required (it does not matter whether there are single parameters, pairs or other tupels, and when there are named global parameters in addition).
  2. The parameters are passed to a Lua module, which analizes them, and performs a loop through the parameter list.
  3. For each action the parameter (or parameters) must be passed to kind of layout template which performs the action, whatever it may be.

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)[reply]

If your parameters are all positional {{{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)
Each time through the loop you get the next enumerated parameter value, call the template on that value, insert the result in the output table. When done looping, concatenate all of the template outputs into a big-damn-string and return that big-damn-string.
A sandbox showing what you have done so far, almost never goes amiss when asking for help.
Trappist the monk (talk) 16:56, 14 January 2020 (UTC)[reply]
@Trappist the monk: thank you very much, your solution works! I never got that idea, but now I am happy that I can solve lots of problems. sarang사랑 12:26, 16 January 2020 (UTC)[reply]

System variables

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)[reply]

Does 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?
Trappist the monk (talk) 13:14, 19 January 2020 (UTC)[reply]
Yes, it is; thank you. I checked through the reference but I could not understand that that is what I needed. sarang사랑 06:29, 21 January 2020 (UTC)[reply]

Improvement to Module:Trim quotes to distinguish single/double quoting from bold and italics wikimarkup

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)[reply]

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)[reply]

Redundant to Module:Page and Module:String. {{#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)[reply]
Thanks, I turned it into {{Stub other}}. ‑‑Trialpears (talk) 09:48, 4 February 2020 (UTC)[reply]

 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)Template:Z48[reply]

 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)Template:Z48[reply]

Connecting Wikipedia articles to reliable sources through new template

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)[reply]

Get all pages in a category

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)[reply]

We've discussed this a few times and believe it to be impossible. You can display the list of members on a page in a way visible to the reader, but there is no way for Lua to read its contents back. Certes (talk) 19:33, 23 March 2020 (UTC)[reply]
It would be possible if mw:Extension:CategoryToolbox would be enabled on this wiki. --Gonnym (talk) 11:08, 24 March 2020 (UTC)[reply]
Actually looking at it now, the doc doesn't show it has an option to get all pages in category, but to check if a page is in a category, so nevermind. --Gonnym (talk) 11:10, 24 March 2020 (UTC)[reply]
The real fix for this and other similar problems is allow lua to fetch the content of strip markers. It used to be, for example, that it was possible to get the content of <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).
Trappist the monk (talk) 12:21, 24 March 2020 (UTC)[reply]

Script to fetch the nutshell text of a given page

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)[reply]

Scripts and lua are not the same thing. At least I don't see them as the same thing. A script runs on your browser. Lua runs when MediaWiki compiles wikitext into the html that your browser displays as an article. If you are looking for a script, then this place is not the right place to be looking.
If you are looking to create shortcut templates that have tooltips where the text of the tooltip is taken from a {{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}}
Trappist the monk (talk) 21:41, 4 April 2020 (UTC)[reply]
See Template:Template parameter value * Pppery * it has begun... 21:43, 4 April 2020 (UTC)[reply]
Something else to consider, wiki markup in a nutshell template. For example, this is the parameter value at WP:EP
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]]).
Converting that to a titletip:
[[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>]]
WP:EP
For the purposes of example, I manually changed the double quotes within the nutshell text to single quotes within the span; those kinds of things will also need to be handled.
Trappist the monk (talk) 22:59, 4 April 2020 (UTC)[reply]
@Sdkb and Trappist the monk: I've started this module. See Module:Nutshell, and User:Guywan/Test2, where it is used. Needs some work yet, I'm no Lua expert. guywan (talkcontribs) 14:49, 5 April 2020 (UTC)[reply]
We always seem to forget that whitespace around template names is allowed. Here is a table of {{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*|',
	}
I recently wrote a function to strip all wikilinks from a template. You might find this useful because who knows how many wikilinks will appear in nutshell text:
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
The 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.
The above doesn't answer the what to do about templates found in a nutshell template (preprocess them, I suppose). What to do about html? I don't think that bullet points are supported in tooltips so string them all together? What about prefixing? Use the default title text or the default title text modified by |title=? Ignore?
Consider using find() to find a particular nutshell pattern then, with the start position returned from find(), use match ('%b{}', start) to get the whole template.
Is it really necessary to use the ustring functions?
Find a better module name. Module:Nutshell implies that it is used to implement all or part of {{nutshell}}; it is not.
Trappist the monk (talk) 15:42, 5 April 2020 (UTC)[reply]
@Trappist the monk: Thanks for your suggestions. I'd say strip anything that isn't sentence-like.
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?
Regards, guywan (talkcontribs) 22:19, 5 April 2020 (UTC)[reply]