Wikipedia talk:Lua

From Wikipedia, the free encyclopedia
  (Redirected from Wikipedia:Lua requests)
Jump to navigation Jump to search

Is there any module to create Wikipedia tables from Wikidata items?[edit]

Example: I want to create a table of books that has columns title, author, genre, description, date, all taken from Wikidata items. I would specify the type of statements (columns) only once, and specify the IDs of the specific books I want to be included on the table. It would create the table automatically, and I wouldn't need to mess with the Wikipedia table template.Iara Ai (talk) 19:42, 12 January 2022 (UTC)[reply]

I'm only just getting my head around the possibilities here. Are you aware of Category:Wikidata_tracking_categories? — Charles Stewart (talk) 23:47, 12 January 2022 (UTC)[reply]
@Iara Ai: please see Module:Wikidata table — Martin (MSGJ · talk) 11:33, 24 February 2022 (UTC)[reply]
@Iara Ai You could always write your own. I've no previous Lua coding experience but with the help of asking at this page, I managed to create Module:Wdtablerow/listed buildings to use in this article Listed buildings at the University of Leeds. Nthep (talk) 15:53, 24 February 2022 (UTC)[reply]
I think we should work together to create one module for this, so all editors can benefit from added features — Martin (MSGJ · talk) 10:50, 25 February 2022 (UTC)[reply]
a good idea. Nthep (talk) 13:48, 25 February 2022 (UTC)[reply]
@Nthep: @MSGJ: yes I was just doing some research just in case something already existed. If nobody takes the lead for this, I'll look into making a module when time allows. Thanks for the reference.Iara Ai (talk) 17:30, 2 March 2022 (UTC)[reply]
You clearly didn't read our comments, because there are two already available! (I think one is bespoke for a particular purpose.) — Martin (MSGJ · talk) 20:58, 2 March 2022 (UTC)[reply]

Errors on List of Marvel Cinematic Universe films[edit]

List of Marvel Cinematic Universe films is currently getting four "Lua error: not enough memory" errors at the bottom of the article. Can someone with knowledge of Lua help investigate where the error is? I feel it might have something to do with the transclusions happening on the article, possibly from Marvel Cinematic Universe: Phase Four. Thanks. - Favre1fan93 (talk) 04:01, 14 February 2022 (UTC)[reply]

A clue is that previewing an edit to the article without changing anything shows Lua memory usage of 52,428,798/52,428,800 bytes, while previewing after deleting the 12 lines with #section wikitext shows 13,761,835/52,428,800 bytes. I don't think the #section would be contributing to the increase from 13MB to 52MB—something in the included wikitext is doing that. Another clue is that there is a massive amount of Wikidata use and I can't see a reason for it—that might be in the included wikitext.
Previewing an edit after replacing the article content with the #section lines, as shown below, gives Lua memory usage 37,592,486/52,428,800 bytes.
{{#section:Marvel Cinematic Universe: Phase One|BoxOffice}}
{{#section:Marvel Cinematic Universe: Phase One|Films}}
{{#section:Marvel Cinematic Universe: Phase One|Response}}
{{#section:Marvel Cinematic Universe: Phase Two|BoxOffice}}
{{#section:Marvel Cinematic Universe: Phase Two|Films}}
{{#section:Marvel Cinematic Universe: Phase Three|BoxOffice}}
{{#section:Marvel Cinematic Universe: Phase Three|Films}}
{{#section:Marvel Cinematic Universe: Phase Three|Response}}
{{#section:Marvel Cinematic Universe: Phase Two|Response}}
{{#section:Marvel Cinematic Universe: Phase Four|BoxOffice}}
{{#section:Marvel Cinematic Universe: Phase Four|Films}}
{{#section:Marvel Cinematic Universe: Phase Four|Response}}
That's all I have time for now. Johnuniq (talk) 06:20, 14 February 2022 (UTC)[reply]
@Johnuniq: It likely could be the "Reception" section, pulling from {{#section:Marvel Cinematic Universe: Phase One|Response}} {{#section:Marvel Cinematic Universe: Phase Two|Response}} {{#section:Marvel Cinematic Universe: Phase Three|Response}} {{#section:Marvel Cinematic Universe: Phase Four|Response}}, all of which use Wikidata pulls to retrieve their Rotten Tomatoes scores and cite elements. - Favre1fan93 (talk) 12:52, 14 February 2022 (UTC)[reply]
Yes, that was my conclusion. The section called by {{#section:Marvel Cinematic Universe: Phase One|Response}} uses 15MB in preview at Marvel Cinematic Universe: Phase One. The expensive memory part seems to be {{RT data|edit}}, which adds 2-3MB for each call. This adds the edit wikidata icon to each reference, which isn't necesssary. The important {{RT data|table}} and {{RT data|access date}} calls are relatively cheap. —  Jts1882 | talk  14:44, 14 February 2022 (UTC)[reply]
I've given up on Wikidata—it's fragile and templates trying to use it are prone to break (although admittedly I haven't seen such breakage for a while), and it uses too many resources, and it has no effective method of monitoring or fixing vandalism. I would raise the issue at a noticeboard at Wikidata and ask if there is a low-cost method of achieving what is being done with {{RT data}}—it's something that needs to be fixed with a redesign. Or, perhaps just remove usage of that template. Johnuniq (talk) 01:53, 15 February 2022 (UTC)[reply]
I placed {{RT data|edit}} in <noinclude>...</noinclude>.[1] Labeled section transclusion apparently doesn't honor noinclude inside <ref>...</ref> so I changed it to #tag:ref in Marvel Cinematic Universe: Phase Three#Critical and public response.[2] That worked. List of Marvel Cinematic Universe films now renders fully with Lua memory usage 34,818,590/52,428,800 bytes. I think the list can do without Wikidata links but I haven't changed to #tag:ref in Phase One and Two so they still transclude the links. PrimeHunter (talk) 03:27, 15 February 2022 (UTC)[reply]
Good result, thanks. Johnuniq (talk) 04:08, 15 February 2022 (UTC)[reply]
Thank you all. PrimeHunter if you don't get to the #tag:ref changes on the Phase One, Two, and Four articles, I can take care of those. - Favre1fan93 (talk) 04:26, 15 February 2022 (UTC)[reply]
The #tag:ref code is unknown to many editors and may confuse some tools and source searches so I wonder whether there is a better solution. PrimeHunter (talk) 04:44, 15 February 2022 (UTC)[reply]
Should the edit wikidata icon and link be included in the reference list? What is the purpose? It doesn't help verify the information. —  Jts1882 | talk  07:52, 15 February 2022 (UTC)[reply]
@Jts1882: because the data is coming from Wikidata, and isn't coded directly on the article, it was added in the event an editor was trying to update the score on the article, and realized that they couldn't do it here, that it had to be done at Wikidata. If that isn't foreseen as an issue of someone unfamiliar with Wikidata not knowing that editing can occur there, then the edit icon can be removed and that probably solves this whole thing. - Favre1fan93 (talk) 17:31, 15 February 2022 (UTC)[reply]
I decided to move the Wikidata edit icons outside the references, which is friendlier for the section transclusion and noinclude tags. An example can be seen with my edit at the Phase One article here. That should solve the original issues, as well as the issue PrimeHunter came across switching to the #tag:ref code. - Favre1fan93 (talk) 20:33, 16 February 2022 (UTC)[reply]
I made an change to Module:EditAtWikidata, which is responsible for the RT edit link. On the revision prior to the noinclusion of {{RT data|edit}}, Special:Diff/1071924802, the Lua memory usage would drop by half from 31 million to 14 million bytes. Edit request pending at Module talk:EditAtWikidata#Performance change. Snævar (talk) 22:58, 17 February 2022 (UTC)[reply]

generating unique IDs[edit]

Here is the requirement: some template needs to assign ID attribute (e.g., in order to use mw-customtoggle-<unique-suffix>). Now, this template might appear multiple times in a page, and each one should have a unique ID (for practical reasons, and in order to have valid HTML). Is there a sane way to ensure that consecutive calls (from different invocations) to the same code will return different results? for obvious reasons, having multiple elements with same ID is not only "invalid html", but also dysfunctional. Did anyone encounter similar challenge before? i hope someone can show me i am stupid, and there's safe and simple way to do it. thanks, peace - קיפודנחש (aka kipod) (talk) 17:45, 18 February 2022 (UTC)[reply]

Use math.random( m, n ) to get pseudorandom number and modify it for the id. —  Jts1882 | talk  18:00, 18 February 2022 (UTC)[reply]
thanks for the advice, but unfortunately, it's not really good: the issue revolves around seeding, Math.random() reseeds on every call, which practically means it's not "pseudo random". if i could guarantee that each call will be executed in a different timeslice, it would work, but even then, the "pseudo random" is just a screen of smoke, and i could just as well use directly os.clock() modulo something.
by reseeding every time, random loses its randomness. calling mw.math.random directly also does not work - when not seeded, it always begins at the same spot. to see what i mean, visit User:קיפודנחש/sandbox: i created a tiny Module:Testrand to demonstrate how consecutive calls to math._random() can return the same value (when the clock did not tick between calls). this happens because each call re-seeds, using the clock, plus some slow moving counters.
admittedly, the parser is (currently) slow enough, such that on consecutive invocations the clock is "guaranteed" to move, but this approach is short-sighted.
allow me bore you with "old-timer" story (personal experience, but i searched and found a link which discusses it): somewhere in the 1980s and 90s, there was a popular development tool called Borland Pascal. now, this product was meant to run on ms-dos, IOW, with no operating system whatsoever for anything other than file access.
the lack of OS created a need for a "delay" library function (e.g., when you wanted to operate some hardware, like UART and such).
BP implemented "delay" in a very naïve and straightforward way, which was reasonable then and would be crazy now: they ran some loop with junk code (or maybe even empty) N number of times, based on the parameter. to translate the parameter of delay() in MS to the number of times the loop should run, a factor is needed, which depends on the speed of the machine.
so, as part of the initialization of the library, a "delay calibration" code was run: the loop was executed large number of times (~64K iirc), the RT clock was sampled before and after to determine the time it took, and divide 64K by the time to get the "delay factor" (so "delay" would execute the loop ms*factor times).
when computers became fast enough, the "delay calibration loop" started executing faster than the clock resolution, and started throwing "divide by zero" exception.
this happens only once, but unfortunately, this one time is during initialization, which basically meant that any program written in BP would fail to start on faster computers (at least, "fail to start reliably" - if you get lucky, your loop straddles a tick...). the sad part is the fact that it did not matter if you ever used or wanted to use "delay()" - vast majority of programs never did, and programmers who did not deal with hardware were typically not even aware of this !@#$% delay, but the "sudden death" affected everyone anyway.
luckily for me, i worked at a large enough company at the time, and we had access to the library source, which allowed me to patch the library (i could not simply remove the calibration, since i needed "delay" to work, as my thing did interface with hardware).
this story is only 12% relevant, but i enjoyed telling it, and i hope some of you enjoyed reading it. won't be surprised if some had first-hand acquaintance with it...
the moral of the story is, do not rely on clock ticks between calls your program makes - some day someone will build a machine fast enough, and you'll find the clock did not tick between the first and 2nd call. under the surface this means that math.random is deeply flawed, as my sandbox demonstrates (BTW, this can be easily fixed: keep a module-wise local variable and ensure that seeding only happens once per invocation).
going back to "random" (not in module math, but in scribuntu: mw.math.random): if it was possible to seed it once per wiki page parsing, such that consecutive calls continue to develop it without seeding, i was fine with going this route, even though there is no guarantee that N consecutve calls will return N distinct value for any N > 1.
however, scribuntu creates a fresh "sandbox" for each invocation, which means random should be seeded per each invocation, which only works when the servers are slow enough, or when mw code is inefficient enough to ensure at least one tick between invocations.
peace - קיפודנחש (aka kipod) (talk) 20:24, 18 February 2022 (UTC)[reply]
By design, different calls with the same parameters are supposed to be totally independent of each other so, for example, one section can be parsed without regard for what is in other sections. I think there should be some restricted method of defining page-global variables (for example, to say "use mdy date formats on this page"), but without that I don't think there is any way of guaranteeing different results with the same parameters. Johnuniq (talk) 22:33, 18 February 2022 (UTC)[reply]

Tables[edit]

I am trying to understand tables in Lua. Please look at my simple example. I am expecting j to be the table {b,2} and I was expecting j[1] to be b. But the output is empty. — Martin (MSGJ · talk) 14:52, 23 February 2022 (UTC)[reply]

You need to set the letters as strings. So surround them with " or '. I'm also a bit surprised that the code ran without an error. Gonnym (talk) 15:03, 23 February 2022 (UTC)[reply]
The b you mentioned is an undefined variable, and it is nil. Lua does not raise errors for undefined vars. Please note the difference between variable name and string. --SolidBlock (talk) 15:10, 23 February 2022 (UTC)[reply]
Which is why it is always a good idea to require('Module:No globals').
Trappist the monk (talk) 15:38, 23 February 2022 (UTC)[reply]
Thanks everyone! It was actually Trappist's comment that led me to solve the real problem I was having [3] — Martin (MSGJ · talk) 17:04, 23 February 2022 (UTC)[reply]
Bear in mind that since the numbers are in quotes ("1", "2", ...), they are strings and will sort like strings so "10" is before "2". Johnuniq (talk) 23:35, 23 February 2022 (UTC)[reply]

Sorting with accents[edit]

Another question. I am using table.sort on Template:French cheeses and I was surprised to see that Époisses is sorted last. I would have expected it come after "E". Is that normal? — Martin (MSGJ · talk) 11:32, 24 February 2022 (UTC)[reply]

I assume it sorts on ASCII codes or other encoding. In ASCII, É is 201 so will come after all alphanumerics. —  Jts1882 | talk  13:32, 24 February 2022 (UTC)[reply]
Yes, you're right. And all the lower case letters are sorted before the uppercase letters. So "z" comes before "A". Arghh! — Martin (MSGJ · talk) 10:32, 2 March 2022 (UTC)[reply]
Wikitext uses UTF-8 encoding and É is two bytes, hex C3 89. The C3 means É will sort after all ASCII characters. There are ugly workarounds that work (most of the time) for simple cases such as European accented letters, but they are horrific. Johnuniq (talk) 23:28, 24 February 2022 (UTC)[reply]
One workaround is to define a table of special characters and where they should be sorted, e.g. function p.preprocessSortName () at Module:Goalscorers (line 469). —  Jts1882 | talk  11:04, 2 March 2022 (UTC)[reply]
In theory, a standard module implementing e.g. azify("Déjà") → "deja" might help. In practice, there are differing opinions on where to sort letters such as ä, even within one language. Certes (talk) 11:52, 2 March 2022 (UTC)[reply]

Accessing template parameters[edit]

I have used the following code to access the first unnamed parameter from a template while also allowing direct use of #invoke

local pframe = frame:getParent()
local input = frame.args[1] or pframe.args[1]

Is this a good way to do it? — Martin (MSGJ · talk) 11:36, 24 February 2022 (UTC)[reply]

Consider Module:Arguments.
Trappist the monk (talk) 13:31, 24 February 2022 (UTC)[reply]
Some of us can't get our heads around Module:Arguments which complicates simple work. Using Arguments works, after you decode the documentation, but your method is fine for most cases. See what function dumphtml does to get two arguments at Module:Dump#L-134. Johnuniq (talk) 23:35, 24 February 2022 (UTC)[reply]
Yes that looks straightforward, thanks! — Martin (MSGJ · talk) 13:04, 25 February 2022 (UTC)[reply]

Regex help[edit]

Could someone help with the regex for the following? I want to scrape the names of the articles from the wikicode, and ignore piped links, i.e.

  • [[Bukhtishu|Bukhtishu family]] -> Bukhtishu
  • [[Ja'far al-Sadiq]] -> Ja'far al-Sadiq

I settled on string.match(article,'%[%[(.+)%|') or string.match(article,'%[%[(.+)%]%]') which seems to work but I think there is probably a more efficient way. Thanks — Martin (MSGJ · talk) 11:44, 24 February 2022 (UTC)[reply]

Maybe string.match(article,'%[%[(.+)%|?.+%]%]')? Not sure if .- would be better.—  Jts1882 | talk  13:24, 24 February 2022 (UTC)[reply]
I think I tried that one. The first capture was being too greedy and including the | as well. — Martin (MSGJ · talk) 14:54, 24 February 2022 (UTC)[reply]
The greediness was why I wondered if (.-) would work. What about ([^|]+) for anything but the pipe? —  Jts1882 | talk  17:08, 24 February 2022 (UTC)[reply]
You could try a regexp like %[%[[^%]]-([^%|%]]*)%]%]. With a [[piped|link]], [^%]]- matches and discards "piped|", then ([^%|%]]*) captures "link". If it's [[unpiped]], [^%]]- comes back empty and ([^%|%]]*) captures "unpiped". It isn't clever enough to handle piped text containing vertical bars such as C|T Group, nor File: links with captions etc. Certes (talk) 01:05, 25 February 2022 (UTC)[reply]

Lua error with Taxonbar?[edit]

Can anyone see what the issue is with this taxonbar for Gea eff (Q4281852)? When I type {{Taxonbar|from=Q4281852}}, I see:

Lua error: bad argument #1 to 'getEntityIdForTitle' (string expected, got nil).

Backtrace:

  1. [C]: in function "error"
  2. libraryUtil.lua:11: in function "checkType"
  3. mw.wikibase.lua:144: ?
  4. (tail call): ?
  5. Module:Taxonbar:475: in function "chunk"
  6. mw.lua:525: ?
  7. [C]: ?

Thanks! Not sure if I should be asking here or Template talk:Taxonbar so I'm asking both places but will respond in both places when the issue is solved. Umimmak (talk) 04:58, 25 February 2022 (UTC)[reply]

I don't know why it occurs, but the problem is that the following gives nil
mw.wikibase.getSitelink('Q4281852')
and that makes Module:ResolveEntityId#L-12 crash with the error shown. Johnuniq (talk) 07:01, 25 February 2022 (UTC)[reply]
@Umimmak: Now that I've had a chance to look at d:Q4281852, the problem is obvious. That item has no entry for enwiki in the "Wikipedia" section near the bottom. Therefore the title at enwiki is nil, and the confusing error results. Module:ResolveEntityId should handle that more gracefully, or at least give an error indicating what the problem is. Hmm, I see Module talk:ResolveEntityId mentions errors in hundreds of articles. The error has temporarily gone away because a recent edit at Module:ResolveEntityId was reverted. Johnuniq (talk) 08:30, 25 February 2022 (UTC)[reply]
(edit conflict)@Johnuniq: hrm… this didn’t use to be an issue. I’m not sure why there needs to be a Wikipedia article for me to get information from Wikidata; I’ve definitely found it useful to have access to the taxonbar when I’m working on an article in a sandbox or draftspace. … but at least it’s working now? Umimmak (talk) 08:31, 25 February 2022 (UTC)[reply]
I was reporting the situation from the point of the module: the "obvious" in my comment was referring to how the code in Module:ResolveEntityId would obviously give that error given that there is no enwiki article for that item. However, the code with that problem has been reverted, so yes, it's working now. I'm sure that if the module is updated again there will be some fix. Johnuniq (talk) 08:36, 25 February 2022 (UTC)[reply]

This was caused by a recent edit to Module:ResolveEntityId which I have just reverted — Martin (MSGJ · talk) 08:37, 25 February 2022 (UTC)[reply]

@Johnuniq, Umimmak, and MSGJ: I think I resolved the issue at Module:ResolveEntityId/sandbox. Please test out {{taxonbar/sandbox}} and let me know. --Ahecht (TALK
PAGE
) 00:16, 26 February 2022 (UTC)[reply]
@Ahecht: There is no wikipedia article (yet) for Gea africana and {{Taxonbar/sandbox|from=Q2158509}} yields:
Looks good to me. Umimmak (talk) 00:23, 26 February 2022 (UTC)[reply]

Automatic watchlist generator[edit]

The original request

Is it possible to create a module that automatically generates a list of pages from those listed in User:WP 1.0 bot/Tables/Project/India (for example, one list for Good Low-importance; another for Featured Mid-importance etc.), so that we can then use Special:RelatedChanges to track the changes. Similarly, another page where the list of the accompanying talk pages is generated for the same reason. Thanks! ---CX Zoom(he/him) (let's talk|contribs) 13:56, 25 February 2022 (UTC)[reply]

Alternatively, a module that takes in pages of a category, for example Category:FA-Class India articles of Mid-importance. Puts them all into a template like the one I created at User:CX Zoom/TestPage5 & thus, creates a related category dependent on the first one. See the template's usage & documentation at User:CX Zoom/TestPage8. This template automatically strips the talk part from the title of the page(s) if any. ---CX Zoom(he/him) (let's talk|contribs) 06:32, 26 February 2022 (UTC)[reply]

You already have categories like Category:FA-Class India articles of Mid-importance, etc. — Martin (MSGJ · talk) 07:20, 26 February 2022 (UTC)[reply]

These categories only consist of the talk pages of the various articles. Not the content pages. As such, it's possible to track changes happening in those categorised talk pages but it's not possible to track changes in the actual content pages using Special:RelatedChanges. I want to have something to do just that. ---CX Zoom(he/him) (let's talk|contribs) 08:27, 26 February 2022 (UTC)[reply]

I realise that I probably wasn't able to make my request clear, and I don't want to waste everyone's time. My request here is superceded by the request below. Thanks! ---CX Zoom(he/him) (let's talk|contribs) 08:38, 26 February 2022 (UTC)[reply]

Categories such as Category:FA-Class India articles of Mid-importance only consist of the talk pages of the various articles. Not the content pages. As such, it's possible to track changes happening in those talk pages but it's not possible to track changes in the actual content pages using Special:RelatedChanges. I want to have something to do just that. For example, Talk:Sholay is a member of this category. When I use Special:RelatedChanges for this category, recent edits on Talk:Sholay show up, but it's not possible to track changes happening in Sholay without going to those articles one by one. ---CX Zoom(he/him) (let's talk|contribs) 08:44, 26 February 2022 (UTC)[reply]

You are in the wrong forum. You would use JavaScript for that, not Lua. Snævar (talk) 18:03, 27 February 2022 (UTC)[reply]

Authority control not recognising accented letters as letters[edit]

Please see Template talk:Authority control/Archive 13#TLS identifier format. We need some regex that will recognise accented letters are being letters. Thanks — Martin (MSGJ · talk) 15:18, 7 March 2022 (UTC)[reply]

Consider changing line 823 to
local idlen = mw.ustring.len (id)
Count unicode characters, not bytes.
Trappist the monk (talk) 15:44, 7 March 2022 (UTC)[reply]

No_globals issue solving[edit]

Over at Module talk:BaseConvert § convert with 'Module:No globals' error?, I have reported an issue (re 'No globals'), and a /sandbox solution. A tech check would be welcome, before pushing it live. -DePiep (talk) 05:18, 12 April 2022 (UTC)[reply]

Solved. -DePiep (talk) 06:32, 13 April 2022 (UTC)[reply]

Lua Pattern matching help[edit]

From the following module call, {{#invoke:WikidataIB|getValue|qid=Q60165516|P131|qual=DATES|fwd=ALL|osd=no|noicon=yes|linked=false}}

Prakasam district (1970–2022), Guntur district (–1970), Bapatla district (2022–)

I would like to extract as given below.

Bapatla district (2022–) Prakasam district (1970–2022),


In general the following matches are required.

1)start has a value, with end value of 2022
2)a start value of 2022 and no end value
3)start has no value, but end value of 2022
3)Start has no value and end has no value

I can get these cases individually as shown below.

case 1[edit]

{{#invoke:String|match|{{#invoke:WikidataIB|getValue|qid=Q60165516|P131|qual=DATES|fwd=ALL|osd=no|noicon=yes|linked=false }}|(%S+ district %(.-2022%))|plain=false}}

Prakasam district (1970–2022)

case 2[edit]

with a different qid

{{#invoke:String|match|{{#invoke:WikidataIB|getValue|qid=Q60165583|P131|qual=DATES|fwd=ALL|osd=no|noicon=yes|linked=false }}|(%S+ district %(2022.-%))|plain=false}}

Bapatla district (2022–)

Case 3[edit]

{{#invoke:String|match|{{#invoke:WikidataIB|getValue|qid=Q60165583|P131|qual=DATES|fwd=ALL|osd=no|noicon=yes|linked=false }}|(%S+ district %(.-2022%))|plain=false}}

Prakasam district (–2022)

Case 4[edit]

with a different qid

{{#invoke:String|match|{{#invoke:WikidataIB|getValue|qid=Q11104042|P131|qual=DATES|fwd=ALL|osd=no|noicon=yes|linked=false }}|(%S+ district)|plain=false}}

Prakasam district

Can you help by giving simple mediawiki template calls to WikidataIB or a complete script to get these values with links and a comma separator, even if the district name has upto three words separate by space? Arjunaraoc (talk) 06:09, 16 April 2022 (UTC)[reply]

After some research I found {{wikidata}} to be a more powerful way to access data from wikidata and used the current parameter to get currently valid data item. Arjunaraoc (talk) 10:32, 2 May 2022 (UTC)[reply]

Error output on a module that should otherwise work[edit]

On my creative-venture wiki on Miraheze, I've recently set up a module called "Find", based on the "find" function at WP's Module:String. Minutes ago, I test-ran it through Special:ExpandTemplates with this sample code (and a couple of variants thereof):

{{#invoke:Find|find|This is a test.|test}}

On WP itself, this should give out "11" as the result. So far, however, these tests over on Miraheze output the error message "Lua error in Module:Find at line 35: attempt to call field '_getParameters' (a nil value)." (Although "_getParameters" isn't referenced anywhere else in this case.)

Sorry, only pinging here because 1) I'm pretty much inexperienced with Scribunto/Lua (being used so much to the old-school style of things with ParserFunctions) and 2) a bit of urgent help is needed. Can someone more qualified troubleshoot this module code and tell me what I missed?

--[[
find

This function allows one to search for a target string or pattern within another
string.

Usage:
{{#invoke:String|find|source_str|target_string|start_index|plain_flag}}
OR
{{#invoke:String|find|source=source_str|target=target_str|start=start_index|plain=plain_flag}}

Parameters
    source: The string to search
    target: The string or pattern to find within source
    start: The index within the source string to start the search, defaults to 1
    plain: Boolean flag indicating that target should be understood as plain
        text and not as a Lua style regular expression, defaults to true

If invoked using named parameters, Mediawiki will automatically remove any leading or
trailing whitespace from the parameter.  In some circumstances this is desirable, in
other cases one may want to preserve the whitespace.

This function returns the first index >= "start" where "target" can be found
within "source".  Indices are 1-based.  If "target" is not found, then this
function returns 0.  If either "source" or "target" are missing / empty, this
function also returns 0.

This function should be safe for UTF-8 strings.
]]
--[[From w:Module:String#L-324]]
--[[This is a partial stand-in for the {{#rmatch:}} function offered by mwe:RegexFunctions, currently disabled on Miraheze per phab:T8866]]
local str = {}

function str.find( frame )
	local new_args = str._getParameters( frame.args, {'source', 'target', 'start', 'plain' } )
	local source_str = new_args['source'] or ''
	local pattern = new_args['target'] or ''
	local start_pos = tonumber(new_args['start']) or 1
	local plain = new_args['plain'] or true

	if source_str == '' or pattern == '' then
		return 0
	end

	plain = str._getBoolean( plain )

	local start = mw.ustring.find( source_str, pattern, start_pos, plain )
	if start == nil then
		start = 0
	end

	return start
end

return str

--Slgrandson (How's my egg-throwing coleslaw?) 12:23, 17 April 2022 (UTC)[reply]

str._getParameters() must be defined in you module somewhere or you will get that error. At Module:String, that function is defined at line 524 et seq. Copy that into you module and see if that fixes your problem.
Trappist the monk (talk) 12:30, 17 April 2022 (UTC)[reply]
Along with "_getBoolean"--which managed to do the trick. Thanks a dozen! --Slgrandson (How's my egg-throwing coleslaw?) 12:57, 17 April 2022 (UTC)[reply]

How do i find specific Module pages?[edit]

I was wondering if there was a way to find the module page to templates if they dont link to them directly? i wanted to improve Plantilla:Ficha de comida (spanish wiki) by translating some of the english (Template:Infobox food) but i cant seem to find the module page for it.Kaidros (talk) 04:58, 20 April 2022 (UTC)[reply]

One useful method is to preview an edit to a page where you replace the contents with a very simple example of using the template. At the bottom, you can view templates used on the previewed page. That includes what modules were called. It's probably es:Module:Ficha. Johnuniq (talk) 05:27, 20 April 2022 (UTC)[reply]

How to use a string read as tablename?[edit]

I have read a variable as string, say 'tFoo'. Now I want that name to be used as a table id: table.insert( 'tFoo', 'someValue1' ). This produces an error (like "error input variable 1: table expected, got string"). How can I use that string as table-name in there? (note: the table name is known beforehand, from a limited list of five, so is declared as local tFoo = {}). In code, essense lines:

local someFunction()
local tFoo = {}
local sInput
   sInput = 'tFoo'
   table.insert( 'tFoo', 'someValue1' ) -- triggers error
   return table.concat( 'tFoo', ";" )
end

DePiep (talk) 06:20, 22 April 2022 (UTC)[reply]

local function someFunction()
	local tFoo = {}
	local sInput
	sInput = 'tFoo'
	table.insert( tFoo, 'someValue1' )
	return table.concat( tFoo, ";" )
end
Johnuniq (talk) 07:23, 22 April 2022 (UTC)[reply]
Hmm, I just read this again. Are you saying you want the name of the table to be determined when the program runs? You can't do that in Scribunto's Lua. You would need to have a series of if...elseif...end tests to work out which table to use. If you describe the problem a bit more I can provide an example. Johnuniq (talk) 07:26, 22 April 2022 (UTC)[reply]
Actually, line 5 should be using the input / replies unchanged OK
   table.insert( sInput, 'someValue1' ) -- triggers error
-DePiep (talk) 07:38, 23 April 2022 (UTC)[reply]

As Johnuniq said, but to avoid if...elseif...end tests use a table of all five tables like in

function p.test()
   local tfoo1 = {1,2,3}
   local tfoo2 = {4,5,6}

   local all_tables = {}
   all_tables["tFoo1"] = tfoo1
   all_tables["tFoo2"] = tfoo2

   local sInput = 'tFoo2'
   local operate_on = all_tables[sInput] or {}
   
   table.insert(operate_on , 'someValue1' )

   return table.concat(operate_on, "; " )
end

This returns "4; 5; 6; someValue1". I introduced "operate_on" for the case your sInput does not match any of the tables, but you probably do not need it. Ponor (talk) 08:41, 22 April 2022 (UTC)[reply]

if i understood the question (and the documentation) correctly, this can be achieved with _G['tFoo'], so the first example should work like so:

local someFunction()
tFoo = {} -- _G[something] only works for globals
local sInput
   sInput = 'tFoo'
-- should work, i did not try: _G[sInput] is the global variable tFoo.
   table.insert( _G[sInput], 'someValue1' ) 
   return table.concat( _G[sInput], ";" )
end

in general it is not a good practice to use globals. if you want a string-indexed table of tables, per the example above, i will only suggest to construct it in a more concise way than the example: one-time variables like the inside tables in the example are just noise. i think it's more readable and maintainable, like so:

function p.test()
   local all_tables = { -- if this is required in multiple places, make it module local rather than function local.
      ["1st table name"] = {1,2,3},
      ["2nd table name"] = {4,5,6},
   }
-- ....

peace - קיפודנחש (aka kipod) (talk) 02:37, 23 April 2022 (UTC)[reply]

Using _G is interesting but it is simply a particular case of Ponor's example where _G is used instead of all_tables. Johnuniq (talk) 03:31, 23 April 2022 (UTC)[reply]
@Johnuniq and Ponor: Thanks both. "determined when the program runs" explains it, and the workaround will gently solve it. I prefer not to use _G or more abstracts, as it is too exotic for me (now). btw, it is to handle this set. -DePiep (talk) 06:02, 23 April 2022 (UTC)[reply]

Recap[edit]

Recap; confusion/mistakes fixed:
Original post by DePiep: I have read a variable as string, say 'tFoo'. Now I want that name to be used as a table id: table.insert( 'tFoo', 'someValue1' ). This produces an error (like "error input variable 1: table expected, got string"). How can I use that string as table-name in there? (note: the table name is known beforehand, from a limited list of five, so is declared as local tFoo = {}).
local function someFunction()
	local tFoo = {}
	local sInput
	sInput = 'tFoo'
	table.insert( sInput, 'someValue1' )
	return table.concat( sInput, "; " )
end
Note by Johnuniq: read the name of the table to be determined when the program runs? You can't do that in Scribunto's Lua.
Workaround by Ponor (shortened here):
function p.test()
   local tfoo1 = {1,2,3}
   local tfoo2 = {4,5,6}

   local all_tables = {}
   all_tables["tFoo1"] = tfoo1
   all_tables["tFoo2"] = tfoo2

   local sInput = 'tFoo2'
   table.insert( all_tables[sInput] , 'someValue1' )

   return table.concat( all_tables[sInput] , "; " )
end
User: קיפודנחש‎ notes about availability of _G.
DePiep (talk) 06:25, 24 April 2022 (UTC)[reply]

Lua object coding (like mw.html)[edit]

I'd like to start programming by object, like building mw.html. Can anyone mention some live modules with good, basic examples? (And more complicated ones maybe). -DePiep (talk) 11:16, 8 May 2022 (UTC)[reply]