Wikipedia:Lua/Requests/Archive 4
This is an archive of past discussions on Wikipedia:Lua. 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 main page. |
Archive 1 | Archive 2 | Archive 3 | Archive 4 | Archive 5 |
Module:Documentation
Just a note that I have finished working on Module:Documentation and it's ready to replace {{documentation}} on all of our template and module pages. I'd like people to comment on it before I put it up live, so if you're interested, please join the discussion at the template talk page. Bug reports, feature requests and general questions are all welcome. :) — Mr. Stradivarius ♪ talk ♪ 07:59, 29 January 2014 (UTC)
- I had a quick skim and have a suggestion regarding the function using "...". As a matter of interest, I believe the following does the job.
local function makeToolbar(...)
local s = table.concat({...}, ' | ')
if s == '' then
return nil
end
return '<small style="font-style: normal;">(' .. s .. ')</small>'
end
- The
{...}
makes a table containing the arguments passed to the function. If any of the arguments to the function could be nil something more would be needed. - There's no need to change the code, but I was looking at "..." recently, and offer the above from that. The module looks great, although I only did a quick skim. Johnuniq (talk) 09:29, 29 January 2014 (UTC)
- You're right, I don't think there are any uses of makeToolbar that have nil values in them, so that would be a simpler way of doing things. But you never know what crazy things coders might add to it in the future, so I figure we may as well keep the version that can handle nil values. Thanks for taking a look at it, by the way. :) And while I'm thinking about it, we should probably decide what we want to do with the automatically generated module documentation. With the current state of Module:Documentation, modules with non-existent /doc pages would look like this, whereas at the moment they look like this. Which one would people prefer? — Mr. Stradivarius ♪ talk ♪ 10:30, 29 January 2014 (UTC)
- The issue is that when there is no doc subpage, the new module would display a "Module documentation" heading before the "You might want to create a documentation page..." blurb. Currently, there is no heading. The heading looks good to me as it presents a consistent format on all module pages—the heading is present but the documentation is blank because there is no doc subpage. Johnuniq (talk) 01:46, 30 January 2014 (UTC)
- You're right, I don't think there are any uses of makeToolbar that have nil values in them, so that would be a simpler way of doing things. But you never know what crazy things coders might add to it in the future, so I figure we may as well keep the version that can handle nil values. Thanks for taking a look at it, by the way. :) And while I'm thinking about it, we should probably decide what we want to do with the automatically generated module documentation. With the current state of Module:Documentation, modules with non-existent /doc pages would look like this, whereas at the moment they look like this. Which one would people prefer? — Mr. Stradivarius ♪ talk ♪ 10:30, 29 January 2014 (UTC)
Automatic module translation is getting there ... advice?
I've been bashing at some code in Module:FormatTemplate/sandbox to translate Wikipedia template code into Lua. Now, with me having been a biology major and the code having evolved organically from a simple module to colorize stuff like "}}}" in a template, and with some bugs still remaining, you can imagine it's not the best code, but I have just managed to translate the first small module with it at Module:FormatTemplate/sandbox/trialruns. (I still need to post-process the output to remove useless concatenations, lines to delete, maybe duplicate statements, etc., and also need a Lua code auto-indentation module) Anyway, I thought I should put a mention here in case someone wants to offer some feedback or suggest design concepts that I should explore. Wnt (talk) 17:24, 29 January 2014 (UTC)
I have now actually managed to auto translate Template:Albumchart, an immense beast of a template, into something that looks almost, but not quite, exactly unlike Lua code. :) Which works! But ... it is such exceptionally bad code as of the moment it actually takes 3-4 times longer than the template. I think that a better variable table and post-processing the module will greatly improve that. Wnt (talk) 15:37, 2 February 2014 (UTC)
- How about working on something simple first, like solving the halting problem! Johnuniq (talk) 23:47, 2 February 2014 (UTC)
- I actually managed to chop the generated code in half, and get the time down pretty close to that of the template, just by taking every statement, stripping out the variable name, putting them in a dictionary, and not creating a new one if a lookup finds it. I'm still working on the concatenation... it's not the halting problem, just a lot of string starts and string ends and substrings amid regrets Lua pattens don't have alternation. What makes this project much easier than other sorts of code translation is that the Wikipedia parser functions have a very limited range of possibilities: no assignments to variables within the template, no loops, etc. Wnt (talk) 00:34, 3 February 2014 (UTC)
mw.html question
Can anyone see what I'm doing wrong in the p.export function in Module:Current events calendar? My mw.html code is generating html like this:
<tr></tr><td>9</td><td>10</td><td>11</td><td>12</td><td>13</td><td>14</td><td>15</td><tr></tr><td>16</td>...
I think this is probably a basic misunderstanding on my part on how mw.html objects interact with block logic, but I can't see how to fix it. — Mr. Stradivarius ♪ talk ♪ 15:04, 3 February 2014 (UTC)
- Well, the
<td>...</td>
pairs seem standard enough; it's these futile<tr>...</tr>
s that worry me. Still, to be clear: is the only problem that you're looking to get rid of these for cleanliness, or is there something else you were trying to accomplish that would affect how the output looks? Because it looks nice right now. Wnt (talk) 16:16, 3 February 2014 (UTC)
- I'm guessing that Mr. S is kind of like me in that I like to have nice readable indented code for the next person that "view source" to see how the page is made. Is it needed? No, not really, but it sure is a LOT easier to read on the other end. — {{U|Technical 13}} (t • e • c) 16:32, 3 February 2014 (UTC)
- The view source option on Wikipedia will get you the invoke, and on the browser will get you text the browser has formatted with linefeeds even in the current version. It's not up to a website to have a bunch of blank space between elements like that just for the source to look nicer, because it would be a waste of bandwidth. Wnt (talk) 16:40, 3 February 2014 (UTC)
- (Actually, the correct answer to that is "All I see now is blonde, brunette, redhead...") Wnt (talk) 16:42, 3 February 2014 (UTC)
- OK, here's the problem -- if you do
local root = mw.html.create('table') root:tag('tr'):tag('td'):wikitext('cell contents') local root2 = mw.html.create('table') root2:tag('tr') root2:tag('td'):wikitext('cell contents')
root returns
<table><tr><td>cell contents</td></tr></table>
but root2 returns
<table><tr></tr><td>cell contents</td></table>
To me, this seems like a basic bug [nay, I suppose it really is a feature; see below] in the HTML function itself. I suppose you can rewrite it where you keep track of the first instance of adding 'td' and add 'tr' just prior to that, but ... this should be fixed. Wnt (talk) 21:40, 3 February 2014 (UTC)
Actually, I'm not sure how to rewrite it. Putting root2 = root2:tag('tr') fixes my simple sandbox example, but doing root = root: in the current events module totally screws it up. Using logic to "keep track of the first instance" isn't going to work because it's a break in the flow of :'s. If it were my module it would be so back to table.insert and table.concat of raw inline CSS by now. I don't have very good patience where complicated objects are concerned. Wnt (talk) 22:03, 3 February 2014 (UTC)
- I worked out how to do it. You just need to use another variable for each row. In your example this would be:
local root2 = mw.html.create('table')
local row2 = root2:tag('tr')
row2:tag('td'):wikitext('cell contents')
- This is the same as what you need to do for Module:HtmlBuilder, so I should probably have tried that before. Maybe there's a more elegant way of doing this, though? — Mr. Stradivarius ♪ talk ♪ 23:54, 3 February 2014 (UTC)
- Hmmm... you call a function, row2:tag, to affect the value of root2... it seems like object oriented programming has met up with 'spooky action at a distance'! I have to say, I never understood what was so bad about just putting together these strings yourself. Wnt (talk) 00:14, 4 February 2014 (UTC)
- I've tried that, and it is a world of pain. You have to worry about unclosed tags, whether you need to have a space before style="xxx", etc. It's just a lot easier to use a library to abstract all of that stuff away. This edit to Module:List should give you an idea of how much unnecessary work you have to do otherwise - and the HTML in that module is fairly simple. — Mr. Stradivarius ♪ talk ♪ 00:19, 4 February 2014 (UTC)
- Hmmm... you call a function, row2:tag, to affect the value of root2... it seems like object oriented programming has met up with 'spooky action at a distance'! I have to say, I never understood what was so bad about just putting together these strings yourself. Wnt (talk) 00:14, 4 February 2014 (UTC)
- (edit conflict)i don't know. first and foremost, there is no "prohibition" on building the whole thing as text yourself (after all, this is what we did before the "mw.html" library was added), but it's much less readable to other editors. still, if you feel more comfortable going raw, maybe this is what you should do.
- second, to me, it makes perfect sense: calling mw.html.create() generates a new html element. calling element:tag() adds a new tag to this element, and while doing so, also returns a reference to this new tag, that can be manipulated further. the original element still contains the newly created tag - think of it as having 2 references to the same thing. take this example:
local a = {} -- new, empty table
local b = {12, a} -- another table, whose 2nd element is a
a[1] = 44 -- now a is not empty anymore - it has one element
- now, if you "flatten" b, you'll find somewhere in it the value 44 (IOW, b[2][1] is 44), even though this value was never added explicitly to b.
- maybe i just did not understand what you said, and just made a perfect ass of myself, but if i did understand you, then i think my simpler example actually demonstrates the same behavior that baffled you when "a" and "b" are html elements (aka "tags") instead of simple tables.
- peace - קיפודנחש (aka kipod) (talk) 00:36, 4 February 2014 (UTC)
- OK, after thinking about it and actually reading the reference manual entry, this actually makes sense. I'd been thinking of it as simply adding annotations rather than creating nodes. Wnt (talk) 08:31, 4 February 2014 (UTC)
- (In a sense, it still is a bug in that one would expect a mw.html functions to return only valid HTML from a tostring() operation on one of their objects. Trying to add a td outside of a tr ought to be some kind of error, at least usually. But admittedly, we wouldn't be happy to have slower execution speed so that it can double check everything put through it, especially when users are adding CSS attributes for Internet Explorer and other such non-standard browsers, so how much should it check?) Wnt (talk) 16:44, 4 February 2014 (UTC)
- i do not think we should expect too much of the mw.html functionality, and i am not sure it would even be good: you can manufacture part of the html as pure text - you can even manufacture some of it outside the module (e.g., in the template, or even outside of that). so we can't require that it will be "valid html", i think. however, we *can* require that it will be "consistent html", i.e., it will close any tag it opens itself, the attributes will be consistent etc. it may not be perfect, in which case we need to file a bug report (e.g.: what happens when the value of an attribute contains a quote? do we generate broken html? i did non test this case - it's just an example of something that *might* go wrong), but none of the problems you describe above are of this ilk. peace - קיפודנחש (aka kipod) (talk) 17:37, 4 February 2014 (UTC)
Module:AutoPortals
I'd like to propose a Module:AutoPortals. It will:
- invoke Module:Portal bar
- find portals associated with article's talk page
- add them to itself
Example:
- We have the World Bank article
- Module goto talk header on its talk page (Talk:World Bank)
- extracts portal boxes from associated WikiProject boxes (Globalization portal, Business and economics portal, International relations portal, etc.)
- Adds {{Portal bar}} template to the article and them to it
It will make portals process much more easier and automates synchronization with adding portals from talk page.
Please comment, --Rezonansowy (talk • contribs) 15:00, 12 December 2013 (UTC)
- This sounds hard to do. The hard part would be getting the portal names from the WikiProject banners. First, we don't have a reliable way to tell what templates are WikiProject banners and what aren't. And second, we don't have any way that I can think of to get a list of portal names from a WikiProject banner invocation. I suppose this could be possible if we altered Template:WPBannerMeta to output portal metadata, but then you would have to preprocess all the banner templates to find the data, and those templates are heavy, so it might affect article loading times. So, all in all, I think it's probably best to stick with doing it manually. — Mr. Stradivarius on tour ♪ talk ♪ 23:03, 12 December 2013 (UTC)
- Here's my solution:
- Lua finds in a talk page every template which starting with WikiProject (e.g. {{WikiProject Globalization}}, {{WikiProject Economics}})
- Get content from its {{WPBannerMeta}}
{{{PORTAL}}}
param - Put it in {{Portal bar}}
- Here's my solution:
- That's all! What do you think about it? --Rezonansowy (talk • contribs) 23:27, 13 December 2013 (UTC)
- The difficult part is step two - Lua can't see inside the WikiProject template to see what text was passed to the
{{{PORTAL}}}
parameter. Also, many projects use redirects to point to their talk page banners, so step one is not reliable. (See Template:MILHIST for example.) Sorry, but I just don't think that this idea is going to work. — Mr. Stradivarius ♪ talk ♪ 01:24, 14 December 2013 (UTC)
- The difficult part is step two - Lua can't see inside the WikiProject template to see what text was passed to the
- I give up....let's create a task for bot to avoid doing it manually, bot will be much better solution. --Rezonansowy (talk • contribs) 01:31, 14 December 2013 (UTC)
- OK, I dunno if this is a sane way to do it, but it does do it: [1] (I use frame:preprocess() to get the final talk page, hunt through for Portal X:X portal links [though I don't check X = X, is there any simple syntax to do that?], and then call the module [rather inefficiently I suppose, with another frame:preprocess, which can be avoided]. Wnt (talk) 05:04, 4 January 2014 (UTC)
- While this will work, I wouldn't call it a sane way of doing things. This way you have to parse everything on the talk page, notably the WikiProject templates, which will probably take you over the 10 second Lua time limit and give you script errors on quite a few pages. I've just thought of a much better way of doing this, though - in Wikidata. If we can work out a way to automatically add portal data to a page's Wikidata entry, we can just grab that data from Wikidata and add those portals to the article. Or maybe Wikidata entries already include portal info? I shall have to investigate. — Mr. Stradivarius on tour ♪ talk ♪ 06:33, 4 January 2014 (UTC)
- Hmmm... I hadn't expected it to take 10 seconds to display the talk page, but it certainly isn't necessary to frame:preprocess the entire page content; in fact it will remove potential false positives from talk page discussions to take only the content up to the first header, or even just the first N characters. It's a pity getContent() can't be set to deliver just the first section, but at least the reference manual doesn't mention such an option. Wnt (talk) 11:05, 4 January 2014 (UTC)
- While this will work, I wouldn't call it a sane way of doing things. This way you have to parse everything on the talk page, notably the WikiProject templates, which will probably take you over the 10 second Lua time limit and give you script errors on quite a few pages. I've just thought of a much better way of doing this, though - in Wikidata. If we can work out a way to automatically add portal data to a page's Wikidata entry, we can just grab that data from Wikidata and add those portals to the article. Or maybe Wikidata entries already include portal info? I shall have to investigate. — Mr. Stradivarius on tour ♪ talk ♪ 06:33, 4 January 2014 (UTC)
@Mr. Stradivarius on tour:, @Wnt: So, what now? --Rezonansowy (talk • contribs) 16:49, 9 January 2014 (UTC)
- Maybe I misunderstood - when you used the word "propose" at the top, I thought you meant to write the module yourself and just wanted feedback about the idea, so I thought the sandbox code I posted would be enough to get you started and you could optimize from there. Are you requesting for us to write Module:AutoPortals? Wnt (talk) 16:57, 9 January 2014 (UTC)
- I wish to write it myself but I've no experience with Lua. I really don't know how to do it. Will it be as slow as Mr. Stradivarius said? --Rezonansowy (talk • contribs) 08:04, 11 January 2014 (UTC)
- Well, this wasn't really a beginner project, so before I lost track of it I tried coding up AutoPortals, trying to minimize the running time. However, it still takes 1.8 seconds, which is questionable when we consider that there may be more important processor-pigging modules in an article, and that is only after putting all of the templates in the example I was using (Talk:World Bank) in the list of templates to strip. (You'll see it in the code) There is another approach possible, namely, checking ONLY for WikiProject portals and expanding only those, but it requires the user to hand-check and rename any calls like {{WPIR}} in the article talk page to something starting "WikiProject" or they lose those portals. Still, I think that may be the way to go; I'll have to fool with ExpandTemplate and see how it works. Wnt (talk) 17:23, 12 January 2014 (UTC)
- How about doing it with Wikidata? That would be faster and less error-prone, and would also benefit smaller wikis who could reuse your work. — Mr. Stradivarius ♪ talk ♪ 17:35, 12 January 2014 (UTC)
- My impression from the time I looked at Wikidata is that they're not set up to do anything that they didn't plan to do. I couldn't edit a full page at once, I couldn't access properties except from the page they wanted me to access them from, and the list of "properties" they maintain was very specific and they didn't want to expand them for, say, holding protein amino acid sequences. I have the impression if there's anything they come up with that is useful for me, they'll design and implement it themselves ... until then, my attitude is "I'll believe it when I see it." If you want to come up with a Wikidata solution go right ahead, but I'm just not even thinking about them. Wnt (talk) 17:55, 12 January 2014 (UTC)
- Alright, you prodded me to retest one of my peeves, and I found a way to access the other articles' properties! - see [2] Wnt (talk) 19:19, 12 January 2014 (UTC)
- And now the feature is gone, because it has "no useful purpose". That seals it. I have nothing to do with Wikidata, period - anything that will ever be done with Wikidata will be done by its proprietors. Wnt (talk) 19:29, 11 February 2014 (UTC)
- Well, the reason was more like "it's subverting the links table" rather than just "it has no useful purpose", and that was never really an intended feature. But you may be right that we shouldn't expect Wikidata to allow this functionality. In which case, the method remaining is to get a bot to do it. It could work like this: an editor places the text
{{auto-portals}}
in an article, which adds the page to a hidden category. A bot is programmed to patrol this category, and add the portals based on the WikiProject Banners on the talk page. Having a bot do this would be better than having a Lua module do it, because a bot would only have to parse the talk page once (or once every day, more likely), whereas a Lua module would have to parse it every time the article was rendered. This would still leave the problem of working out what templates are WikiProject templates, and would still require mapping WikiProject templates to portals, neither of which are particularly easy things to do because of all the edge cases. But someone might be willing to do the programming work if you ask at WP:Bot requests. — Mr. Stradivarius ♪ talk ♪ 03:18, 12 February 2014 (UTC)
- Well, the reason was more like "it's subverting the links table" rather than just "it has no useful purpose", and that was never really an intended feature. But you may be right that we shouldn't expect Wikidata to allow this functionality. In which case, the method remaining is to get a bot to do it. It could work like this: an editor places the text
- How about doing it with Wikidata? That would be faster and less error-prone, and would also benefit smaller wikis who could reuse your work. — Mr. Stradivarius ♪ talk ♪ 17:35, 12 January 2014 (UTC)
- Well, this wasn't really a beginner project, so before I lost track of it I tried coding up AutoPortals, trying to minimize the running time. However, it still takes 1.8 seconds, which is questionable when we consider that there may be more important processor-pigging modules in an article, and that is only after putting all of the templates in the example I was using (Talk:World Bank) in the list of templates to strip. (You'll see it in the code) There is another approach possible, namely, checking ONLY for WikiProject portals and expanding only those, but it requires the user to hand-check and rename any calls like {{WPIR}} in the article talk page to something starting "WikiProject" or they lose those portals. Still, I think that may be the way to go; I'll have to fool with ExpandTemplate and see how it works. Wnt (talk) 17:23, 12 January 2014 (UTC)
- I wish to write it myself but I've no experience with Lua. I really don't know how to do it. Will it be as slow as Mr. Stradivarius said? --Rezonansowy (talk • contribs) 08:04, 11 January 2014 (UTC)
How about a mw.file api
I propose we start a core mw.file api. The primary reason of why I think we should add a mw.file module is because I think it's important to get the source width and height. There are multiple templates like Template:Multiple image and Template:Wide image that depend on the user inputting values manually into the template invocation in order to deal with things calculating widths and heights of containing elements Multiple image details one such case, but we could also merge Template:Wide image Template:Panorama and Template:Tall image into a single template, able to take into account both widths and heights, simply because we would get access to the exact aspect ratio of the original image. —TheDJ (talk • contribs) 14:12, 13 December 2013 (UTC)
It should probably look something like this ? —TheDJ (talk • contribs) 13:47, 13 December 2013 (UTC)
- mw.file.new(mw.title)
- (expensive)
Creates a new file object for the current revision of this file title.
File objects
A file object has a number of properties and methods. Most of the properties are read-only.
- title
- mw.title corresponding to this file
- archiveName
- shared or local
- url
- link to the original file
- getImageInfo()
- Returns table with
- mime
- the mime type this file is registered with
- mediaType
- The mediawiki mediatype: BITMAP/AUDIO/VIDEO etc
- height
- The original height of the file
- width
- The original width of the file
- size
- Bytesize of the file
- pages
- The amount of pages that this file consists of
- duration
- duration of the media clip if this is a media clip ?
- animated
- Animated gif/png/video
Later
- metadata
- The metadata table for a file also see bugzilla:41498
- languages
- array of languages supported for this file (how to get metadata for a language ? mw.file.new(mw.title, language) ?
Might not be needed ?
- sha1
- the SHA1 of this image file (what would we use this for ?)
- user
- The username who uploaded
- timestamp
- The time of the upload
- comment
- The upload comment
Thumbs
- mw.file.newThumb( mw.title [, size [, page [,language]]] )
- (expensive)
- isThumb
- page
- The page that this is a thumb of
- thumbMime
- thumbHeight
- thumbWidth
- thumbUrl
Comments
This has been requested by a few other people as well - see bugzilla:52522. This would make sense as the next big feature for Scribunto, but I suppose that depends on whether we have any developer time to spare. — Mr. Stradivarius ♪ talk ♪ 14:06, 13 December 2013 (UTC)
- imageinfo could also have duration (in seconds) for AUDIO/VIDEO. -- WOSlinker (talk) 14:15, 13 December 2013 (UTC)
- (edit conflict) Actually, judging from gerrit:67588, this is just about done, but is waiting on another patch. I'm not sure what the schedule is there, though. — Mr. Stradivarius ♪ talk ♪ 14:18, 13 December 2013 (UTC)
- That is just the exif metadata. Ergo what in the above table would count as 'metadata' property of a mw.file. —TheDJ (talk • contribs) 14:25, 13 December 2013 (UTC)
- I really like this idea, but I sure wish we could have a getContent() in there also. Especially for SVG images! Wnt (talk) 22:48, 20 December 2013 (UTC)
- mw.message is useful here also. out = mw.message.newRawMessage("[[File:Example.png]]"):parse() will yield HTML source including 'width="275" height="297"'. By contrast, out = out .. mw.text.unstrip(frame:preprocess("[[File:Example.png]]")) is not expanded and so displays as an image. (That doesn't mean we don't want the library though!) Wnt (talk) 17:41, 13 January 2014 (UTC)
- Now that that technique doesn't work anymore, I'll work on getting a nice interface built. Jackmcbarn (talk) 20:00, 12 February 2014 (UTC)
There's a new request at Module talk:Flags. Something seems to be wrong with the Soviet Union flags. I thought it might be useful to include the request here, in case not many editors watch that page. Thanks! - tucoxn\talk 05:47, 13 February 2014 (UTC)
- The problem got fixed. It was probably related to redirect creations and file renaming on Commons. See my response at Module talk:Flags for more. Thanks! - tucoxn\talk 09:44, 13 February 2014 (UTC)
Need help
I'm from Bengali wikipedia. I need help to fix a problem. Problem is: when we use template parameter like this Rivers of {{{countryname}}} sometime template gives wrong result. Parameter Exemple: {{{countryname}}}ের নদী (Rivers of {{{countryname}}}); If countryname=বাংলাদেশ it gives বাংলাদেশের নদী (correct) but If countryname=অস্ট্রেলিয়া it gives অস্ট্রেলিয়াের নদী which is wrong.
This problem can be fix easily using module: 1) Module needs to find the last letter of word (বাংলাদেশ - here last letter is শ, অস্ট্রেলিয়া - here last letter is া ) 2) If last letter is া , ি , ী , ু , ূ , ৃ , ে , ৈ , ো , ৌ then add only র (অস্ট্রেলিয়া - here last letter is া so module should be add only র means অস্ট্রেলিয়ার) 3) If last letter is ই then add only য়ের 4) If last letter is none of those (point no. 2,3) then add ের 4) If last letter is অ, আ, ঈ, উ, ঊ, ঋ, এ, ঐ, ও, ঔ, ক, খ, গ, ঘ, ঙ, চ, ছ, জ, ঝ, ঞ, ট, ঠ, ড, ঢ, ণ, ত, থ, দ, ধ, ন, প, ফ, ব, ভ, ম, য, র, ল, শ, ষ, স, হ, য়, ড়, ঢ় then add ের
Someone please help bn wiki by creating a module. --Aftab1995 (talk) 17:42, 15 February 2014 (UTC)
- Can the algorithm required be explained using English examples? I guess you need a template: let's call it fix for now. The "Rivers of" is just an example? So you need something like this:
{{fix|{{{countryname}}}}}
- Assume countryname is "abcd". Fix gets the last character ("d"). It's not the last letter? If countryname is "abc123", the last letter is "c" and the last character is "3". I know that's not a likely scenario, but programs are pretty dumb and they have to told exactly what to do. I imagine it's the last character that is wanted.
- The result of fix is the input (countryname) with some text appended. That text depends on the last character.
- 1) Is the above correct? If so, it's pretty easy and I'll have a go. You can put the following into the "Debug console" when editing any module, and press Enter to see the result.
=mw.ustring.sub('(বাংলাদেশ', -1)
- The result is "শ" (the last character). Hmmm. That result looks different from what you show above, but my editor claims your character is hex 09b6, and so is my character. That's way above my head. I'll try the other examples later, but perhaps there is a combining characters problem? I have noticed that mw.ustring regards each codepoint as a character (which to my simple mind seems reasonable), yet I understand that a language like Bengali can combine codepoints to form different characters. That might be tricky.
- Is a "fix" template needed? Or do you want to directly call the module? Suppose the module is Module:Fix, then you could use:
{{#invoke:fix|{{{countryname}}}}}
- Please correct any misunderstandings above, and tell me what name to use for the template (if it is wanted), and what name to use for the module. I'm a bit uneasy about the combining character issue, and testing may show that mw.ustring.sub is not enough. Johnuniq (talk) 01:55, 16 February 2014 (UTC)
- "Rivers of" is just an example & you're right, i wanted the last character (i assure you that last character will be a letter). 1) Yes, above is correct.
- I want a template where i call the module. Module name isn't a problem, you may use "fix" or "এর" (If needed, i can change the name later). Please create a module as a test. Aftab1995 (talk) 15:46, 16 February 2014 (UTC)
- I don't think it's working properly yet, but I have created a module and template (I had to call it "adjust" because "fix" is in use). See bn:User:Johnuniq/adjust. Johnuniq (talk) 03:23, 17 February 2014 (UTC)
- Done
- This appears resolved for now as the module is apparently working. It had a very interesting copy/paste bug that I will probably never understand: when I copied the wikitext for the Bangla characters above into my local file, I somehow ended up with a space character combined with some of the Bangla codepoints. For example, where my module had " া", the thing in quotes is actually a space combined with a codepoint: in hex, it is four bytes: 20+e0+a6+be, whereas only the last three bytes were wanted. Johnuniq (talk) 01:18, 18 February 2014 (UTC)
- I don't think it's working properly yet, but I have created a module and template (I had to call it "adjust" because "fix" is in use). See bn:User:Johnuniq/adjust. Johnuniq (talk) 03:23, 17 February 2014 (UTC)
External links
At the small Wikipedias it's hard to find Lua experts so I hope you don't mind if I ask here. I would like to correct the external links (Identificants) in this article:
The article is based on:
At Lua template no. 2 there must be an error but I can't find it. --Marc Alioria (talk) 01:56, 7 March 2014 (UTC)
- At en.wiki, "external link" means something like http://example.com in an "External links" section at the end of some articles. I think you are referring to the "Q851164" that appears in the article, which should be some text extracted from Wikidata. As far as I can tell, oc:Modèl:Wikidata is a template which invokes oc:Module:Wikidata, and the only other module involved on the article linked above is oc:Module:Wikidata/formatatge. Is "Escolaritat Q851164" the problem you mean? Are there any pages with the Wikidata template which work? The #2 item above is a template which does not directly use Lua, although it might be calling the Wikidata module via its template. Johnuniq (talk) 02:46, 7 March 2014 (UTC)
- With external links I've meant the section "Identificants": VIAF http://13.219.148.195/. The correct link would be: https://viaf.org/viaf/232494275/. --Marc Alioria (talk) 03:00, 7 March 2014 (UTC)
- I've found what I think is the problem: this edit removed the
{{{3}}}
parameter from oc:Modèl:Linha Wikidata extèrne, which is being used by oc:Modèl:Infobox identificacions autoritats. I'll double-check that that's the only thing broken, and fix it if everything looks ok. — Mr. Stradivarius ♪ talk ♪ 03:25, 7 March 2014 (UTC)- Yep, that looks like the problem - after expanding the templates, those external links show up as wikitext like
[http://1020032421 1020032421]
, which is being interpreted as an IP address by Chrome and probably other browsers too. If you add the missing URL portion, it turns into a valid link about the article's subject: 1020032421. — Mr. Stradivarius ♪ talk ♪ 03:38, 7 March 2014 (UTC)- Good! I was getting lost. Johnuniq (talk) 03:45, 7 March 2014 (UTC)
- And now fixed here. In the end, it didn't have anything to do with Lua. :) — Mr. Stradivarius ♪ talk ♪ 03:50, 7 March 2014 (UTC)
- Good! I was getting lost. Johnuniq (talk) 03:45, 7 March 2014 (UTC)
- Yep, that looks like the problem - after expanding the templates, those external links show up as wikitext like
- I've found what I think is the problem: this edit removed the
- With external links I've meant the section "Identificants": VIAF http://13.219.148.195/. The correct link would be: https://viaf.org/viaf/232494275/. --Marc Alioria (talk) 03:00, 7 March 2014 (UTC)
Function needed
I need a small function isList() that returns true if a string is a wikilist, simply by checking if the first character is "*", "#", ";" or ":". — Edokter (talk) — 13:16, 7 March 2014 (UTC)
- i believe something like
{{#invoke:String|find|source = <YOUR STRING>|target = ^[*#;:]|plain=false}}
- should work, no? note that using "source=" means your string will be trimmed - if you want to allow for spaces (i.e., "<Space>#bla" will fail while "#bla" succeeds), drop the "source =" part: "your string" should be the first param after "find". this will return 0 if your string is not a list, and 1 if it is.
- if you meant for longer string that might contain newlines, then the request should be defined more precisely - what is expected to happen when some of the lines begin with one of [*#:;] but not all? (examples below)
- {{#invoke:String | find | source = b#la | target = ^[*#;:] | plain = false}} => 0
- {{#invoke:String | find |source = #bla | target = ^[*#;:] | plain = false }} => 1
- peace - קיפודנחש (aka kipod) (talk) 17:01, 7 March 2014 (UTC)
- Using string.match() inside Lua module: Hence, inside a Lua module, the functionality would be as follows:
if string.match(str,'^[*#;:]') ~= nil
then hey = "There is a list item in str."
end
- Note the regex has been set to match the start-of-line by caret "^" and would not yet match text with a leading space (such as " :"); however, to also match with leading spaces, then include regex " *" to match zero-or-more spaces, as: string.match(str,'^ *[*#;:]') to match list items even with lead spaces. -Wikid77 (talk) 04:21, 9 March 2014, 04:16, 10 March 2014 (UTC)
- for the benefit of future generations who might look in the archive, i want to note that the last example, namely
string.match(str,'^ *[*#;:]')
, is not only useless, it's positively wrong: the "zero or more" quantifier, "*", applies only to the single character preceding it (semicolon), and not to the whole "no-break" marker, " ", as Wikid77 seems to imply. (note: i injected a hidden directional character so the non-breaking-space will be visible when reading the page). "real" regex supports grouping (using parenthesis), which would make this possible, but lua pattern matching does not support it. peace. קיפודנחש (aka kipod) (talk) 00:49, 10 March 2014 (UTC)- Well, I had used ' ' for typesetting the text, not as a literal ampersand-n-b-s-p as part of a regex pattern, but I have re-typeset those by using nowrap text; sorry for the confusion. So, the example I gave is not only quite useful, it's positively correct (I have 2 extensive university degrees in computer science, so that is why I was instantly familiar with the regex issues). -Wikid77 04:16, 10 March 2014 (UTC)
- @Wikid77: if it was meant for *real* whitespace rather than for non-breaking space, then your snippet may be technically correct, but it's lacking, and, of course, completely useless: lines beginning with spaces are parsed as "pre" elements and not as lists, even if the first character after the space is "*":
- Well, I had used ' ' for typesetting the text, not as a literal ampersand-n-b-s-p as part of a regex pattern, but I have re-typeset those by using nowrap text; sorry for the confusion. So, the example I gave is not only quite useful, it's positively correct (I have 2 extensive university degrees in computer science, so that is why I was instantly familiar with the regex issues). -Wikid77 04:16, 10 March 2014 (UTC)
- for the benefit of future generations who might look in the archive, i want to note that the last example, namely
* this is not a list element
- beyond its uselessness, it's "lacking", because when one wants to match whitespaces, one should use %s rather than <Space>. this will match tabs and other whitespaces also. peace - קיפודנחש (aka kipod) (talk) 13:26, 10 March 2014 (UTC)
- List items preceded by spaces: At first I thought you were joking, but you actually seem to believe what you are saying. Instead, list items in Wikipedia can have leading spaces, such as in wp:parser functions (#ifexpr, lc, etc.). For example:
- 1. {{uc: ::::::* Bullet line}} =
- BULLET LINE
- 2. {{#ifexpr: 1 = 2-1 | {{{x| :::::::* bullet}}} }} =
- bullet
- 1. {{uc: ::::::* Bullet line}} =
- Hence, for the way Wikipedia actually works, the regex pattern I gave is actually quite useful to match a list item with leading spaces. However, some whitespace characters literalize the list-items, such as " " which cannot precede an asterisk bullet. It is important to test notions in real markup, rather than imagine something as being "useless" in some imaginary world. -Wikid77 22:01, 10 March 2014 (UTC)
- But then again, parser functions and templates passed to Lua will have already been expanded, so for Lua scripts it does make sense to assume that wikitext lists must start at the start of a line. — Mr. Stradivarius on tour ♪ talk ♪ 22:52, 10 March 2014 (UTC)
- Well, you could assume parameters have no leading spaces, but it would be wrong; see below: "#Parser keeps lead spaces in unnamed parameters". -Wikid77 17:51, 11 March 2014 (UTC)
- But then again, parser functions and templates passed to Lua will have already been expanded, so for Lua scripts it does make sense to assume that wikitext lists must start at the start of a line. — Mr. Stradivarius on tour ♪ talk ♪ 22:52, 10 March 2014 (UTC)
- (ec) Parser functions strips whitespace (so do template parameters for that fact). The only thing I am interested in is the first character being
[*#;:]
. — Edokter (talk) — 22:54, 10 March 2014 (UTC)- Only named parameters strip outer spaces (and the whitespace tabs): "#Parser keeps lead spaces in unnamed parameters". -Wikid77 17:51, 11 March 2014 (UTC)
- (ec) Parser functions strips whitespace (so do template parameters for that fact). The only thing I am interested in is the first character being
Here's my effort:
local function isList(s)
-- Returns true if s starts with the characters "*", "#", ";" or ":".
-- Otherwise returns false. Will produce an error if s is not a string.
if s:find('^[*#:;]') then
return true
else
return false
end
end
That's all you need to detect strings starting with [*#;:]
. — Mr. Stradivarius ♪ talk ♪ 23:28, 10 March 2014 (UTC)
- And thinking about it, you could do that in even less code:
local function isList(s)
-- Returns true if s starts with the characters "*", "#", ";" or ":".
-- Otherwise returns false. Will produce an error if s is not a string.
return s:find('^[*#:;]') ~= nil
end
- Not sure if there's any merit in doing that over the one above, though. — Mr. Stradivarius ♪ talk ♪ 23:34, 10 March 2014 (UTC)
- Nice and short. What happens if an error is raised? — Edokter (talk) — 23:38, 10 March 2014 (UTC)
- If an error is raised when running from #invoke, you get the lovely big red "script error" message. :) To avoid that, you have three basic options. The first is to make sure that you will only pass strings to the function. This is actually not so hard, as argument values passed from #invoke are always strings. (Argument keys can be numbers, however.) The second is to check the type of s before doing the matching. You can make it return nil if s is not a string, and true or false otherwise. That works like this:
- Nice and short. What happens if an error is raised? — Edokter (talk) — 23:38, 10 March 2014 (UTC)
local function isList(s)
-- Returns true if s starts with the characters "*", "#", ";" or ":".
-- Otherwise returns false. Will return nil if s is not a string.
if type(s) ~= 'string' then
return nil
end
return s:find('^[*#:;]') ~= nil
end
- Or this:
local function isList(s)
-- Returns true if s starts with the characters "*", "#", ";" or ":".
-- Otherwise returns false. Will return nil if s is not a string.
if type(s) == 'string' then
return s:find('^[*#:;]') ~= nil
else
return nil
end
end
- In a similar vein, you can also convert s to a string before matching it, by using
s = tostring(s)
. But type checking is more elegant. The third is to try and catch the error by using pcall - although I think just checking the type of s is neater. — Mr. Stradivarius ♪ talk ♪ 23:59, 10 March 2014 (UTC)- about "neatness": it is very common (and neat, if you ask me) in lua to use boolean shortcut for this purpose exactly: so instead of if..then..else..end, one can simply write this will return either false (not a string), 'nil' (not a list) or the first character. usually this is good enough, but if you prefer "true" rather than the found character, use
return type(s) == 'string' and s:find('^[*#:;]')
this pattern is very common in lua, it makes the code shorter and more concise, and getting familiar with it is helpful. i use it all the time - maybe sometimes to a fault... peace - קיפודנחש (aka kipod) (talk) 23:23, 11 March 2014 (UTC)return type(s) == 'string' and s:find('^[*#:;]') and true
- about "neatness": it is very common (and neat, if you ask me) in lua to use boolean shortcut for this purpose exactly: so instead of if..then..else..end, one can simply write
- In a similar vein, you can also convert s to a string before matching it, by using
Parser keeps lead spaces in unnamed parameters
Note how the unnamed parameters retain any leading spaces/tabs, when invoking a Lua function:
- f1. {#invoke:String|find|*bullet|target=^[*#:;]|plain=false}} = 1
- f2. {#invoke:String|find| *bullet|target=^[*#:;]|plain=false}} = 0
- f3. {#invoke:String|find|source= *bullet|target=^[*#:;]|plain=false}} = 1
- f4. {#invoke:String|find| *bullet|target=^%s*[*#:;]|plain=false}} = 1
In case f2, the find() is unable to match with the lead-spaces and gives result "0" as a no-match, but in case f3, with the named parameter ("source="), the parser has omitted the outer spaces/tabs. To handle extra spaces/tabs, before a list-item, the regex pattern in case f4 uses "^%s*" to allow multiple spaces/tabs to precede a list-item, such as in " *bullet" with 3 extra spaces. -Wikid77 (talk) 17:51, 11 March 2014 (UTC)
Pattern documentation
This is the Lua pattern documentation: mw:Extension:Scribunto/Lua_reference_manual#Introduction, and [3]. Is there a pattern documentation that does not say "like the regex we all know, except ..."? I need a 101 documentation, so in chapters 1 to 4 the word "greedy" does not appear. If such a documentation exists for regex, that would be great too. -DePiep (talk) 14:50, 7 March 2014 (UTC)
- Start with article "Regex" and remember percent '%' for literals: Because there are so many features, it would be best to tell people to read page "Regex" but beware how Lua uses percent sign '%' as the literalizing character (not standard "\"). Hence to match square brackets in a string, each bracket must be escaped as '%[' and '%]' because regex brackets specify a single-character set. Compare examples:
- 1. {#invoke:String |find|source= aabbcc |target= [.*] |plain=false}} = 0
- 2. {#invoke:String |find|source= a[ab]bcc |target= \[.*\] |plain=false}} = 0
- 3. {#invoke:String |find|source= a[ab]bcc |target= %[.*%] |plain=false}} = 2
- 4. {#invoke:String |find|source= aab[bc]c |target= %[.*%] |plain=false}} = 4
- Note how the brackets only matched (in lines 3 & 4) once they were escaped as Lua '%[' and '%]' and that is bizarre, compared to the typical POSIX backslash format, as '\[' and '\]'. Page "Regex" contains an extensive explanation of the major regex features, with several complex examples to demonstrate the potential power of using regex patterns. Unfortunately, a "Regex 101" guide will require learning the numerous regex patterns, just as "Greek 101" requires learning the 24-letter Greek Alphabet, in alphabetical order; otherwise a student cannot lookup words in a Greek/English dictionary unless knowing the sequence of Greek letters: α-β-γ-δ-ε, etc. Regex is similar to fair-use restrictions for copyrighted images; a student should plan at least 3-5 days of study to understand the major concepts and restrictions in usage.
FYI: It is crucial for students to understand how regex matches are "greedy" and match the longest possible string, as compared to typical human left-to-right, find-the-first-match. In fact, regex's greedy pattern-matching is likely one of the worst design flaws in the history of computer science, and has been a royal pain for over 35 years, requiring new symbols to allow "non-greedy" matches. I would rank greedy matches the same as "implicit declaration" of misspelled variable names, as likely to cause horrific bizarre results. -Wikid77 (talk) 05:36, 9 March 2014 (UTC)
- @DePiep: Try the lua-users wiki. If that's hard to understand, post back here with whatever you're having trouble with, and someone should be able to help you out. Good luck. :) — Mr. Stradivarius ♪ talk ♪ 08:06, 9 March 2014 (UTC)
- Also, for regex, I found regular-expressions.info useful. — Mr. Stradivarius ♪ talk ♪ 21:44, 9 March 2014 (UTC)
- Thanks. I've added the links to the Lua resources page. -DePiep (talk) 16:50, 10 March 2014 (UTC)
- Also, for regex, I found regular-expressions.info useful. — Mr. Stradivarius ♪ talk ♪ 21:44, 9 March 2014 (UTC)
- I don't understand the complaint about greedy pattern matching. If I do {{#invoke:LuaCall|main|x=abaabaaab|y=b(.*)b|string.match(x,y)}} -> aabaaa, sure, that's greedy. But I can do {{#invoke:LuaCall|main|x=abaabaaab|y=b(.-)b|string.match(x,y)}} -> aa just as easily. And the greediness still uses a left to right search; it just doesn't stop until it has to. But it is annoying that the Lua format doesn't accept a number of the Javascript options, so that it's not easily possible to reuse Javascript patterns here. Wnt (talk) 03:21, 13 March 2014 (UTC)
- I tried redigesting the Scribunto manual at [4] - I'm not sure I made anything clearer or in any way better though. Wnt (talk) 03:04, 14 March 2014 (UTC)
- I'm going to reiterate Module talk:LuaCall#I sincerely hope that no one ever actually uses this: I really don't think using that is something we should encourage use of. Anomie⚔ 10:31, 14 March 2014 (UTC)
- I don't understand the criticism. First, to be honest, I don't understand what load(func, chunk) is actually used for. And certainly I don't see any comparison to obfuscated C. What I know is that I find myself making use of this fairly often - most commonly for a string.len measurement of a DYK-related item. I assume it would be legitimate to write a dedicated module for purposes like this, but why bother having a separate module for each one? To be clear, I do understand that going back to LuaCall repeatedly within a single template would quickly become inefficient. Wnt (talk) 14:24, 14 March 2014 (UTC)
- Wnt, I guess you refer to my complaint about greedy. I meant to say that, when starting Lua patterns (or Regex for that matter), explaining "greedy" should not be the first topic. And so, a little hyperbolic, it should be "not in chapter 1 to 4". That is because when I want to learn Patterns from scratch, that is not the essence. To illustrate this with the demo you gave yourself: I first need to know what the meaningful symbols are you use (that is
*().
). Now please don't explain them to me here, it's just to show that I need to learn that first. -DePiep (talk) 14:41, 14 March 2014 (UTC) - Wnt, sounds like you're looking for Module:String#len? — Mr. Stradivarius ♪ talk ♪ 15:24, 14 March 2014 (UTC)
- You're right, that is useful in this case. But I still don't see any reason why that is good but LuaCall is bad. Wnt (talk) 19:56, 14 March 2014 (UTC)
- Wnt, I guess you refer to my complaint about greedy. I meant to say that, when starting Lua patterns (or Regex for that matter), explaining "greedy" should not be the first topic. And so, a little hyperbolic, it should be "not in chapter 1 to 4". That is because when I want to learn Patterns from scratch, that is not the essence. To illustrate this with the demo you gave yourself: I first need to know what the meaningful symbols are you use (that is
- I don't understand the criticism. First, to be honest, I don't understand what load(func, chunk) is actually used for. And certainly I don't see any comparison to obfuscated C. What I know is that I find myself making use of this fairly often - most commonly for a string.len measurement of a DYK-related item. I assume it would be legitimate to write a dedicated module for purposes like this, but why bother having a separate module for each one? To be clear, I do understand that going back to LuaCall repeatedly within a single template would quickly become inefficient. Wnt (talk) 14:24, 14 March 2014 (UTC)
- I'm going to reiterate Module talk:LuaCall#I sincerely hope that no one ever actually uses this: I really don't think using that is something we should encourage use of. Anomie⚔ 10:31, 14 March 2014 (UTC)
this template is apparently very expensive, mainly due to excessive use of parser functions, i think. (some of the pages and templates using it clock at 15 and 20 seconds for parsing(
it's also super complicated. i do not suggest, necessarily, to replace it with something that would use the exact same syntax, though this may not be so bad also.
my suggestion/request is more about thinking, finding and defining better syntax to this functionality, that would make it easier for the editors to create those charts. ideally, the editor would use some "language" to define the relationship between the nodes, without having to worry about the precise layout of the boxes and lines.
unfortunately, i can't think of such syntax myself.
looking at the template's source code, it's clear that this is an unmanageable nightmare - prime candidate for scribunto, IMO.
peace - קיפודנחש (aka kipod) (talk) 20:11, 23 March 2014 (UTC)
- How about this:
{{autochart |node1 = fred |node2 = jane |node3 = joe |fred-text = [[Fred Bloggs]] |jane-text = [[Jane Bloggs]] |joe-text = [[Joe Bloggs]] |fred-sister = jane |fred-child = joe |jane-child = joe |fred-jane-line = dashed }}
- That would produce something like:
Fred Bloggs | Jane Bloggs | ||||||||||||||||
Joe Bloggs | |||||||||||||||||
- That would require a lot more processing in the module than the current system. It would also have to deal with multiple ways of specifying the same information, e.g.
fred-jane-line
andjane-fred-line
would refer to the same thing. It would also have to detect conflicting data, and probably throw errors for it, e.g.fred-jane-line = solid
andjane-fred-line = dashed
. Or another example:fred-child = joe
,fred-sister = jane
andjoe-child = jane
. And probably the hardest part would be working out where to draw the lines, as there are a lot of different possibilities. Thoughts? — Mr. Stradivarius ♪ talk ♪ 00:46, 24 March 2014 (UTC)- not sure. it makes sense, but i think there are a few things supported by current template that may not be possible (it's hard to say, b/c currently the editors have to create the line-art: much more tedious, but also much more freedom).
- also, i think we can get away from limiting ourselves to template syntax (name=value, separated by | ): sometimes you want more elaborated tupples, and the fact that the module can examine the values programatically, allows us do this.
- not to claim that what i did is perfect or even good, but look at the syntax i created in module:chart for the slices in a pie chart: you can use a single parameter, namely "slices", enclose each slice in parenthesis, and define some mandatory and some optional fields. i am not sure this is necessarily better, but it might be: for instance, in your example, there are multiple parameters pertaining to fred:
|node1 = fred |fred-text = [[Fred Bloggs]] |fred-sister = jane |fred-child = joe |fred-jane-line = dashed
- maybe we can have a syntax where all the information about a specific node is in a single argument:
- ( name=Fred : val=Fred blogs : siblings=Jane{solid}; Zoe{dashed} : descendants-Jane=Joe; Jill : descendants-Zoe = Heironimus; Nefertiti )
- this is not a full example, nor a correct one, it's just an illustration to the idea that each node can be fully defined in one place instead of many. i think this would be good, but others may disagree.
- BTW - it may be better not to list the "child" nodes as part of the parent info, and instead list the parents nodes as part of the child info, b/c, as far as i saw, a "child" has at most 2 parents with "Chart" or "Family tree", but a parent can have many children. so a node will look like so:
- (name=Node name : content=Node content : parents=parent1; parent2; line type : siblings=sibling1 (line type); sibling2.... : maybe some more stuff)
- this way, the actual tree may look like so:
{{autochart | some generic option = some value ... | nodes = ( Node 1 info as above ) ( Node 2 ) ( Node 3 ) ... }}
- "generic" here means "option that affects the whole chart".
- my point is that if all the information about a specific node is in one place, it makes life easier to the editors, i believe. peace - קיפודנחש (aka kipod) (talk) 02:22, 24 March 2014 (UTC)
Module request
At nl-wiki we do not have much Lua users active, so I hope you can help me with a request.
We need a module in Lua that splits a certain string and returns the value of specific pieces of that string. The input is for example type:forest_scale:25000_region:NL
.
- If the template asks for type, then it returns 'forest' (and if none a '0' or empty), if it asks for scale, it returns '25000' (and if none a '0' or empty), and if it asks region it returns 'NL' (and if none a '0' or empty).
- The order in which the pieces of the string are can be different and should not matter, for example
type:forest_scale:25000_region:NL
should give the same results asscale:25000_type:forest_region:NL
. - It is possible that some string will not contain all of them, if for example type: is missing, a '0' or an empty answer should then be the result.
- It is possible users made a mistake and did add something unrecognisable to the string. If we ask for 'error' it then should give back the unknown part(s) or give '1' as output if there are problems/unrecognisable parts in the string.
- It is possible that the type: is city(...) with on the ... a number, for example
type:city(20000)_region:NL
. Then if the template asks for type, then it returns 'city' and somehow we should be able to extract that number separately. Like with a second parameter or with city/20000 so we can split it with a parserfunction.
Who can help me with this request? Thanks! Romaine (talk) 18:16, 24 March 2014 (UTC)
- I've had a go at creating this at Module:User:Mr. Stradivarius/sandbox5. I'll post usage instructions here in a little while. — Mr. Stradivarius ♪ talk ♪ 00:18, 25 March 2014 (UTC)
- In the mean while Martijn Hoekstra was so kind to write a module for me. Thanks for all the efforts. Romaine (talk) 01:21, 25 March 2014 (UTC)
- So, it works like this:
{{#invoke:User:Mr. Stradivarius/sandbox5|main||scale}}
→ Error: no input code specified{{#invoke:User:Mr. Stradivarius/sandbox5|main|scale:25000_type:forest_region:NL}}
→ Error: no field specified{{#invoke:User:Mr. Stradivarius/sandbox5|main|scale:25000_type:forest_region:NL|scale}}
→ 25000{{#invoke:User:Mr. Stradivarius/sandbox5|main|scale:25000_type:forest_region:NL|field=scale}}
→ 25000{{#invoke:User:Mr. Stradivarius/sandbox5|main|scale:25000_type:forest_region:NL|type}}
→ forest{{#invoke:User:Mr. Stradivarius/sandbox5|main|scale:25000_type:forest_region:NL|region}}
→ NL{{#invoke:User:Mr. Stradivarius/sandbox5|main|foobar|region}}
→{{#invoke:User:Mr. Stradivarius/sandbox5|main|foobar|error}}
→ Error: the scale, type and region fields are missing{{#invoke:User:Mr. Stradivarius/sandbox5|main|scale:25000_type:forest_region:NL|error}}
→{{#invoke:User:Mr. Stradivarius/sandbox5|main|scale:25000_type:city(30000)_region:NL|type}}
→ city{{#invoke:User:Mr. Stradivarius/sandbox5|main|scale:25000_type:city(30000)_region:NL|type|citydata=yes}}
→ 30000
- Feel free to use my version or Martijn's version, whichever suits you better. If there's anything about my version that you want me to change, just ask. And if you're happy with it, I can make it configurable to work in different languages too. Best — Mr. Stradivarius ♪ talk ♪ 01:45, 25 March 2014 (UTC)
- So, it works like this:
- In the mean while Martijn Hoekstra was so kind to write a module for me. Thanks for all the efforts. Romaine (talk) 01:21, 25 March 2014 (UTC)
Is there any way to save some value between two separate module calls?
I have one function that add some values to the list. And other function should return that values.
Is there any way to do it?
As for now I can't find any mechanism to save some data between different module calls on the one page (using #invoke).
Can you help me please?.. Vitalik (talk) 17:53, 23 March 2014 (UTC)
- No, there is no way to save a value between separate #invoke calls. This is by design, so that individual parts of a page can be parsed separately from other parts. This means that there is no possibility of this ability being added to Scribunto in the future, either. — Mr. Stradivarius ♪ talk ♪ 00:17, 24 March 2014 (UTC)
- Oh, it's a really pity.. But great thanks for the answer!
I'm sory, can I ask one more question (it is about this subject but not about Lua).
There is an extension: Extension:Variables, that allows to use variables through template lagnuage (so it will be possible to save some information between template calls). Is it possible to activate this extension and what should we do for this? (I'm from russian wiktionary and this possibility can be very useful for us). Vitalik (talk) 21:11, 24 March 2014 (UTC)
- Oh, it's a really pity.. But great thanks for the answer!
- I'm pretty sure the answer is no, for the same reason - the WMF technical people want to be able to parse individual parts of articles without those parts being dependent on parsing the other parts. — Mr. Stradivarius ♪ talk ♪ 23:44, 24 March 2014 (UTC)
- There is deliberately no way to do this. If such a way is found, it will be considered a bug, and will be "fixed" (removed). mw:Extension:Variables will not be deployed here either. See bugzilla:7865 for the reasons why not. Jackmcbarn (talk) 20:59, 27 March 2014 (UTC)
- I'm pretty sure the answer is no, for the same reason - the WMF technical people want to be able to parse individual parts of articles without those parts being dependent on parsing the other parts. — Mr. Stradivarius ♪ talk ♪ 23:44, 24 March 2014 (UTC)
table with automatic summation
i was asked on hewiki, and as of now, could not think of something useful rnough, simple enough for editors, and doable.
here is the deal: the user wants to create a template to be used in articles about athletes, more specifically footballers (as in the game played with a ball kicked by feet, not the game played with a "football" thrown by hand). this user would like to be able to create "stats" tables, with special rows for "subtotals" and "totals". for instance, imagine one row of the table for each year in the footballer's carre, and columns for "goals", "assists", "saves", "red cards" etc. if the footballer played in several clubs, for each club the columns should be totalled (these are the "subtotal" rows), and then the last row is the total for the whole thing (either total the "subtotal" rows, or else total everything *but* the subtotal rows). the template should work reasonably well for players that switched club many times (let's say 10), but also for players who played in few or even just one club.
for some historical athlete, be it Puskás or The Babe, i guess it doesn't make too much of a difference - use lotus 123 (or visicalc, or quattro or something) to calculate the totals and enter it as static data. however, for an active player, updating the stats after each season and re-calculating the subtotals and totals is both a drag, and a reliable source of bugs, errors and mistakes, so the automatic summing looks very attractive.
now, i would hate to create a module custom made just for this, because it makes sense that a "summing table" can be used in other contexts, maybe for other athletes, and maybe for other things also (who knows what - say, the amount of different kinds of wood chucked by some notable woodchuck over different decades or something). does such a template/tool exist? is it worthwhile to create it? can you suggest a syntax that makes sense and will be convenient enough to the editors? peace - קיפודנחש (aka kipod) (talk) 05:30, 1 April 2014 (UTC)
Weatherbox module & template
Is it possible to localized (number localization) Weatherbox module & template for other wikipedia. (On the Bengali wikipedia, currently we use old weatherbox code. I try to use new code but it gives result in english.) If it is possible, please do it. I hope someone will help me to fix it, thank you. --Aftab1995 (talk) 16:46, 7 April 2014 (UTC)
- I don't have time to take on a new project at the moment, but I did something for hiwiki a few months ago that may be of interest. They wanted a module to translate between Hindi and English digits. Frankly I never understood why they wanted some of the requested features, but I gather they wanted something they could drop in a template/infobox that would accept numbers in either format, and produce results in a specified format (by format, I just mean using Hindi or English digits, and with correct group separators). The weather template/module appears to need something much more complex, but bear in mind that some simple tweaks to the hiwiki module may be useful for other purposes. See hi:User:Johnuniq/number which has relevant links. Johnuniq (talk) 22:40, 7 April 2014 (UTC)
- I can hazard a guess as to the "why": they probably wanted to be able to use Hindi numerals in the #expr and #time parser functions. — Mr. Stradivarius ♪ talk ♪ 05:19, 8 April 2014 (UTC)
- I'm not a expert. so it is very difficult for me to understand :( . it would be great, if someone take this. :) Anyway, Thanks for answer. --Aftab1995 (talk) 16:44, 8 April 2014 (UTC)
Automate WP:GA subpages' article counts
Hello!
So if you look at the various subpages of WP:GA, like for example Wikipedia:Good articles/Natural sciences, you'll see that each section has "(XX articles)" after it. This is currently maintained by hand. I believe this should be possible to do with some regexes and Lua, you'd just need to count the number of wikilinks in each section.
So, does this sound like a good idea for a Lua module? And if so, would someone be willing to write the necessary code? If not, I'm just going to write a bot to do it; but I would prefer not to. ;) Thanks, Legoktm (talk) 07:51, 12 April 2014 (UTC)
- That's not a job for a module. While certain ugly tricks are possible, essentially a module produces output from the input that it is given—it cannot (without hacks) read text from elsewhere on the page. What would be possible would be to devise some new syntax, and get people to use that syntax rather than doing what they are doing now. There would be one template per section, and the items would be passed as arguments to the template. The template would pass the arguments to a module which would generate the wikitext, including the trailing count. Johnuniq (talk) 09:37, 12 April 2014 (UTC)
- Agreed. Doing text parsing like that with Lua is quite resource-intensive, so it makes sense to just have a bot to do the work once rather than to do it on every page parse. I actually tried to do this with Module:Rfx, but I found that even after I optimised the code as much as I could it still took about 0.7 seconds to process an average RfA. That's just a bit too much to add to processing time, I think. If we're doing it with Lua the fastest thing would be to move the whole list to module space, but I'm not sure other editors would go for that. — Mr. Stradivarius on tour ♪ talk ♪ 11:42, 12 April 2014 (UTC)
- Is 0.7 seconds really worth worrying about? Especially when it's imposed only on the rare occasions when someone edits a page? Especially when it's a page edited as seldom as these? I mean, when you try to debug a loop you can be imposing 10 seconds every time you do a preview, and I didn't think you really had to sweat that. I still remember Wikid77 going on about pages that took more than a minute to preview overall, due to templates. Wnt (talk) 21:09, 16 April 2014 (UTC)
- Agreed. Doing text parsing like that with Lua is quite resource-intensive, so it makes sense to just have a bot to do the work once rather than to do it on every page parse. I actually tried to do this with Module:Rfx, but I found that even after I optimised the code as much as I could it still took about 0.7 seconds to process an average RfA. That's just a bit too much to add to processing time, I think. If we're doing it with Lua the fastest thing would be to move the whole list to module space, but I'm not sure other editors would go for that. — Mr. Stradivarius on tour ♪ talk ♪ 11:42, 12 April 2014 (UTC)
@Legoktm: The simple way to do what is wanted would be to change the way those pages are constructed. For example, WP:Good articles/Natural sciences#Mineralogy currently has this wikitext:
=====Mineralogy===== [[Kauri gum]] – [[Nassak Diamond]] – [[Vanadinite]] – <small> (3 articles)</small>
That could be changed to something like:
=====Mineralogy===== {{#invoke:join|ga |[[Kauri gum]] |[[Nassak Diamond]] |[[Vanadinite]] }}
And someone would write the ga
function in Module:Join (I'll do it). It would output the required wikitext. Johnuniq (talk) 02:03, 13 April 2014 (UTC)
- Also agreed - if we're going to do it in Lua then this is probably the most painless way. We should get a consensus from the editors involved with GAs before we refactor all of the lists, though. — Mr. Stradivarius ♪ talk ♪ 16:08, 13 April 2014 (UTC)
- On an implementation note, I think from an abstraction point of view, it would be better to create a new module to implement this feature (perhaps one that can be generalized to different classes of articles). It could of course internally call the join module if necessary. isaacl (talk) 17:08, 13 April 2014 (UTC)
- I think that the entire header and footer can be transferred to a module, which provides a good opportunity for the text in between to be run through it en masse. But I don't really understand all the places this is used from - in particular, why the subpage needs to be checked. Since there are a bazillion links to it, it's hard for me to see where it's transcluded. (I've just fiddled about with this at Module:Good Articles - that isn't really right yet; I still haven't really understood the data I'm messing with. But it should be proof of principle.) Wnt (talk) 23:18, 15 April 2014 (UTC)
- What about algorithm that wraps whole page, where paragraphs and simple wikilinks to good articles are passed as separate positional arguments i.e.:
{{#invoke:join|count| ...bla bla bla... =====Mineralogy===== |[[Kauri gum]] |[[Nassak Diamond]] |[[Vanadinite]] | ... bla bla bla ... }}
Each argument that match simple wikilink pattern ([[good article]]) is counted and printed in decorated form between next such item. Before every other item the counter is flushed to output and reset to zero, and the other item is simply copied to output. If the wikitext include some pseudo magic words they can be replaced in post processing (i.e. __TOTALGOODARTSINTHEPAGE__) with some statistics collected during generating the page. There is also a way to pass some named arguments to define i.e. separator to define the decorative separator between links, format with presentation of the counter, total with the pseudo magic word to replace in post processing etc. Paweł Ziemian (talk) 18:49, 16 April 2014 (UTC)
- Wrapping an entire page in a #invoke isn't really a good idea. Jackmcbarn (talk) 18:58, 16 April 2014 (UTC)
- This is the approach I started to take in Module:Good Articles, but indeed it involves some decision making that may come to be too constrictive, or else not really add much convenience. Johnuniq's first approach above is the same thing on a smaller scale that might turn out to be more manageable. The trade-off to consider is that if we have to stud the article full of "pseudo magic words", maybe those should just be calls to separate modules rather than parameters in some all-encompassing module with delusions of grandeur. Wnt (talk) 20:16, 16 April 2014 (UTC)
- I did some tests on plwiki with wrapping whole page and I must admit that this is not good idea. There is an error Out of time error for LUA (the limit is set to 10 seconds). However, if I wrapped a few top level sections everything went fine within 3 seconds. I did this with passing whole contents as argument #1, and splitting the parameter to separate lines with analyzing them directly in Lua script. So the wikicode in the page looks like this:
- This is the approach I started to take in Module:Good Articles, but indeed it involves some decision making that may come to be too constrictive, or else not really add much convenience. Johnuniq's first approach above is the same thing on a smaller scale that might turn out to be more manageable. The trade-off to consider is that if we have to stud the article full of "pseudo magic words", maybe those should just be calls to separate modules rather than parameters in some all-encompassing module with delusions of grandeur. Wnt (talk) 20:16, 16 April 2014 (UTC)
{{#invoke:test|counter| ...bla bla bla... =====Mineralogy===== [[Kauri gum]] • [[Nassak Diamond]] • [[Vanadinite]] ... bla bla bla ... }}
- There was 13 main sections (= 13 invokes) and about 2200 lines of text. I used very simple test to determine number of links, looking for [[ at the beginning of line except [[File:, which points to picture that is sporadically used to decorate the page. If such wrapping method would be used on every set of links separately, then the script code might be simplified even more to determine number of lines in the argument, assuming that there is one link per line. Paweł Ziemian (talk) 21:25, 16 April 2014 (UTC)
- I implemented the algorithm for this wiki. You may try to wrap a section from list of good articles within {{#invoke:Sandbox/Paweł Ziemian/test|goodCounter|...}} and see preview of the article. The Biology section took more than 7 seconds in Lua, so analysing the wikicode is not good idea, but works for small set of data. Paweł Ziemian (talk) 21:56, 16 April 2014 (UTC)
- Well, my example wrapping the page at Module talk:Good Articles takes about 1.6 seconds -- it would be faster, except for some reason I can't get gsub to accept false or nil as the third parameter to avoid doing any substitutions when all I want to do is count with it (which is what the documentation says it can do). Wnt (talk) 03:05, 17 April 2014 (UTC)
- Please just implement what I wrote above, which would be close to instantaneous, not to mention robust and comprehensible. Johnuniq (talk) 07:35, 17 April 2014 (UTC)
- I just finished up my version of WP:GA/NS at Module talk:Good Articles. Mine took 2.1 seconds compared to the original's 1.8 seconds on preview. There is now not a single div in the page source. Admittedly there are a lot of parameters to keep track of though. Wnt (talk) 14:17, 17 April 2014 (UTC)
- Please just implement what I wrote above, which would be close to instantaneous, not to mention robust and comprehensible. Johnuniq (talk) 07:35, 17 April 2014 (UTC)
- Well, my example wrapping the page at Module talk:Good Articles takes about 1.6 seconds -- it would be faster, except for some reason I can't get gsub to accept false or nil as the third parameter to avoid doing any substitutions when all I want to do is count with it (which is what the documentation says it can do). Wnt (talk) 03:05, 17 April 2014 (UTC)
- I implemented the algorithm for this wiki. You may try to wrap a section from list of good articles within {{#invoke:Sandbox/Paweł Ziemian/test|goodCounter|...}} and see preview of the article. The Biology section took more than 7 seconds in Lua, so analysing the wikicode is not good idea, but works for small set of data. Paweł Ziemian (talk) 21:56, 16 April 2014 (UTC)
- There was 13 main sections (= 13 invokes) and about 2200 lines of text. I used very simple test to determine number of links, looking for [[ at the beginning of line except [[File:, which points to picture that is sporadically used to decorate the page. If such wrapping method would be used on every set of links separately, then the script code might be simplified even more to determine number of lines in the argument, assuming that there is one link per line. Paweł Ziemian (talk) 21:25, 16 April 2014 (UTC)
I asked for opinions at WT:Good articles#Proposal to change syntax of WP:GA subpages. Johnuniq (talk) 10:21, 17 April 2014 (UTC)
- I think the best solution is using the essential replace function from Wnt code in the way the Johnuniq proposed initially:
=====Mineralogy===== {{#invoke:tools|countLinks| [[Kauri gum]] – [[Nassak Diamond]] – [[Vanadinite]] – }}
- which can be visible in action as
Mineralogy
Kauri gum –
Nassak Diamond –
Vanadinite – (3 articles)
- I did some tests on plwiki using the same page as above with 132 invokes and the Lua time usage is 0.203/10.000 seconds. Paweł Ziemian (talk) 19:31, 17 April 2014 (UTC)
- The Lua time usage from previewing Module talk:Good Articles just now was 0.179/10.000 seconds, but admittedly this isn't a direct comparison since I'm not sure exactly what you previewed. In any case it should be clear that the time is not really a factor here - at this point, the question is what syntax the people who actually edit these articles would prefer to upkeep. If they want to make the conversion to one of these formats we also can write a module to do that automatically too. Wnt (talk) 15:08, 19 April 2014 (UTC)
- There are always pro and cons. The clue is what are the weights. Your solution looks good for me, however it designed only for one very specific usage. The solution presented as first is simpler and more generic, and can be used anywhere where the counter seems to be interesting, but suffer from the fixed presentation format. Next argument is usability. If the module is wrapped in some template it can be easy usable by most people, which are familiar with wikikode or use visual editor. The last factor is maintainability. Whenever any change in presentation form is required it is always easier to make it in wikicode, which is more robust for many mistakes. Formating wikicode from Lua script is difficult, due to remember both the wikicode syntax wrapped in Lua syntax. Paweł Ziemian (talk) 19:27, 19 April 2014 (UTC)
- Someone pointed me that generating whole sections in templates or #invoke causes that you have to always edit whole page. There is no [edit] link near to section title at any level. Paweł Ziemian (talk) 12:42, 20 April 2014 (UTC)
- The Lua time usage from previewing Module talk:Good Articles just now was 0.179/10.000 seconds, but admittedly this isn't a direct comparison since I'm not sure exactly what you previewed. In any case it should be clear that the time is not really a factor here - at this point, the question is what syntax the people who actually edit these articles would prefer to upkeep. If they want to make the conversion to one of these formats we also can write a module to do that automatically too. Wnt (talk) 15:08, 19 April 2014 (UTC)
Shogi board
Hi,
I am wondering if it would be possible to make something like Module:Chessboard that can be used to make shogi diagrams. There is a shogi diagram template being used to create such diagrams on Japanese Wikipedia, but I am unable to get it to work on English Wikipedia. A shogi board looks sort of like a chess board, but there are some important differences:
- A shogi board is 81 'squares' (9 files by 9 ranks)
- Each 'square' is not really a perfect square; it is more rectangular with the height (or length) about 1.2 or 1.3 times the width.
- Each 'square' is the same color. In a typical shogi diagram, this is usually the color white (or the color of the paper), and the borders/lines are typically black. Actual shogi boards can come in a variety of colors, but they are usually in a natural wood (beige/tan) color. Very similar to go boards in both style and color, just with less 'squares'.
- Files are typically labeled usually the arabic numerals "1" through "9". Although ranks are typically labeled using Japanese kanji numerals, some English-language publications use the lower case letters "a" through "i" instead. Files are labeled from right to left, and ranks are labeled from top to bottom. Each square is indicated by a number-letter combination so the uppermost-right square is "1a", the bottommost-left square is "9i" and the long diagonal from right to left, top to bottom would be "1a, 2b, 3c, 4d, 5e, 6f, 7g, 8h, 9i". Unlike chess diagrams, labels for files and ranks in shogi diagrams only typically appear at the top and right sides of the board respectively.
- On a tradition shogi board that are 4 dots at the intersections of certain 'squares' to indicate piece-promotion zones. These are are located at the intersection of the following squares: 3g-3f-4g-4f, 6g-6f-7g-7f, 3d-3c-4d-4c, and 6d-6c-7d-7c. See here for an example of what I am referring to.
- Shogi pieces are usually indicated in a single kanji character. I believe the files used for the pieces in shogi diagrams in Japanese Wikipedia articles are available in Wikicommons. I am only interested in a diagram for traditional shogi and not any shogi-variants so the following pieces would have to be displayed: p="pawn", l="lance", n="knight", s="silver", g="gold", b="bishop", r="rook", and k="king". Since some shogi pieces can promote, the following are also needed: d="promoted rook", h="promoted bishop", t="promoted pawn", ps="promoted silver", pn="promoted knight" and pl="promoted lance".
- Unlike chess, shogi pieces are all the same color so there is no "black" or "white". The player who moves first is called "sente" and the player who moves second is called "gote". Typically, sente's pieces are located at the bottom of the board (like the white pieces in chess) and gote's pieces are located at the top of the board (like the black pieces in chess). In , sente is indicated by the letter "s" and gote by the letter "g" so the sente's king would be "ks" and the gote's king would be "kg".
- Captured shogi pieces are called "pieces-in-hand" and can be used on subsequent moves. In show diagrams, pieces-in-hand are usually shown on the sides of the board: the right side for sente and the left side for gote; however, they can be shown at the top (for gote) and bottom (for sente) if it is easier to do.
Well, I hope that's enough information for anybody interested in doing something like this. Please feel free to leave a message on my talk page, if you have any questions or need any further info. Thanks in advance - Marchjuly (talk) 07:34, 22 April 2014 (UTC)
- I figured out a way to get the template I mentioned above to work on English Wikipedia so I guess there's no need for a Module:Shogiboard to be created. However, if somebody wants to take a crack at making one and has any shogi related questions, then please let me know and I'll answer what I can. Thanks again. - Marchjuly (talk) 04:07, 23 April 2014 (UTC)
mw.html library nil behaviour
For those interested, there is a discussion open about a possible change in behaviour of the mw.html library at the main project talk page. — Mr. Stradivarius ♪ talk ♪ 13:16, 22 April 2014 (UTC)
For next loop
Hi, Maybe it already exists but could not fid it. But I'm looking for a for next loop possibility for something like this:
- {{Result|races=5}} that translate to:
- For x := 1 to races
- ||Race {{{x}}}
- Next x
And produces: Race 1 Race 2 Race 3 Race 4 Race 5
How do i request this? Thanks in advance.NED33 (talk) 11:21, 9 April 2014 (UTC)
- {{for loop}}? Jackmcbarn (talk) 12:07, 9 April 2014 (UTC)
- Not quite i think. This is the result I need for a variaty of no of races with and without a medalrace variant. like these examples.
Rank | Country | Helmsman | Crew | Race 1 | Race 2 | Race 3 | Race 4 | Race 5 | Race 6 | Race 7 | Race 8 | Race 9 | Race 10 | Total | Total – discard | ||||||||||
Pos. | Pts. | Pos. | Pts. | Pos. | Pts. | Pos. | Pts. | Pos. | Pts. | Pos. | Pts. | Pos. | Pts. | Pos. | Pts. | Pos. | Pts. | Pos. | Pts. |
Rank | Country | Helmsman | Crew | Race 1 | Race 2 | Race 3 | Race 4 | Race 5 | Race 6 | Race 7 | Race 8 | Race 9 | Race 10 | Race 11 | Race 12 | Race 13 | Race 14 | Race 15 | Medalrace | Total | Total – discard | ||||||||||||||||
Pos. | Pts. | Pos. | Pts. | Pos. | Pts. | Pos. | Pts. | Pos. | Pts. | Pos. | Pts. | Pos. | Pts. | Pos. | Pts. | Pos. | Pts. | Pos. | Pts. | Pos. | Pts. | Pos. | Pts. | Pos. | Pts. | Pos. | Pts. | Pos. | Pts. | Pos. | Pts. |
Rank | Country | Helmsman | Crew | Race 1 | Race 2 | Race 3 | Medalrace | Total | Total – discard | ||||
Pos. | Pts. | Pos. | Pts. | Pos. | Pts. | Pos. | Pts. |
- NED33 _/) 12:50, 9 April 2014 (UTC)
- I wrote at Wikipedia:Help desk#Counters in a template that the goal could be achieved with something like 16 repetitions of
{{#ifexpr:{{{races}}}>N|colspan=2 {{!}} '''Race N''' {{!!}}}}
where N runs from 1 to 16. Such repetition is common in templates and I still doubt it's worth a module if there isn't a general for loop which can be used. PrimeHunter (talk) 13:35, 9 April 2014 (UTC)
- I wrote at Wikipedia:Help desk#Counters in a template that the goal could be achieved with something like 16 repetitions of
- The current situation is different but simular. The major problems that I have with it are: riged in case there are 17 races and that the code is hardly human readable/maintainable. But if there is no other solution I leave it like it is. However I am hoping on a more elegant solution than the current.NED33 _/) talk 14:18, 9 April 2014 (UTC)
- It's quit silent on this one:-) Is there anyone coming for the rescue or do I leave it as it is.NED33 _/) talk 18:27, 11 April 2014 (UTC)
- The current situation is different but simular. The major problems that I have with it are: riged in case there are 17 races and that the code is hardly human readable/maintainable. But if there is no other solution I leave it like it is. However I am hoping on a more elegant solution than the current.NED33 _/) talk 14:18, 9 April 2014 (UTC)
- This is sort of frustratingly trivial, yet invites a really involved response. We certainly can hack together a simple for loop to output columns like this - it would make a good first Scribunto module if you want to try yourself. On the other hand, it just about begs us to write up a "Django" module that implements some substantial subset of the features in Django (web framework)/Jinja style templates, so that editors could wrap part of their text in an invoke and be free to do increments, for and while loops, substitute parameters, etc. Possibly a middle approach, with fewer features, is most viable, but then we have to make decisions about the syntax. It's just kind of tickling away, asking for a good general approach. Wnt (talk) 22:39, 18 April 2014 (UTC)
- Would this be a starting point for the syntax?
- {{ForNext|from = expr1|to = expr2|increment = expr3|statments = statm}}
- Would this be a starting point for the syntax?
- So that the coding of above example could look like something like this:
- {{ForNext|from = 1|to = races|increment = 1|statments = '
- {{#ifeq|{{{counter}}}|{{{races}}}
- |Medalrace
- |Race {{{counter}}}'
- }}
- {{#ifeq|{{{counter}}}|{{{races}}}
- }}
- {{ForNext|from = 1|to = races|increment = 1|statments = '
- So that the coding of above example could look like something like this:
- I'm available to do tests or help but I have no experience with Scribunto not Django what so ever. Regards _/)_/)_/) ˷˷˷˷˷˷˷˷ _/) NED33talk 08:58, 20 April 2014 (UTC)
- Well, to begin with, Django templates use a {% whatever %} syntax which fortunately is ignored by the Wikitext processing. The article gives a few examples. But covering a large subset of it would be quite a lot of work, and I'm reluctant to dive into it right now - I have too many old projects I've left hanging already that I ought to finish... Wnt (talk) 06:06, 25 April 2014 (UTC)
Help debugging script
I'm trying to write a lua script that will generate an "Awards and decorations" table for military officers (something like this. I wrote a draft script (still needs tweaking) at Module:Sandbox/DD4235/Military Decorations, but weird stuff happens when I try to #invoke it. User:DD4235/Military Decorations shows what's happening: first is the wikitext generated; seems fine. Then is what the wikitext renders as; something is wrong with the templates. Finally is what happens if the wikitext is copy-pasted back into a page; it works perfectly fine. Can anyone show me what I'm doing wrong? Thanks. DD4235 (talk) 04:19, 21 April 2014 (UTC)
- This is because wikitext passed from Lua is not expanded. So if you return the text
{{done}}
from a Lua module, it will display as {{done}}, not as Done. This is for performance reasons - the major reason for enabling Lua on Wikimedia wikis is to avoid the need to expand a lot of templates, which have a heavy performance penalty. To work around this, you can use frame:expandTemplate or frame:preprocess to expand the wikitext while in Lua. However, a better solution performance-wise would be to convert Template:Ribbon devices to Lua and use the require function to call that Lua module from your sandbox module. Hope this helps. — Mr. Stradivarius ♪ talk ♪ 06:55, 21 April 2014 (UTC)- Having said that, substituting the module should work without using frame:expandTemplate, as substitution happens at an earlier stage of processing. Try using
{{subst:#invoke:Sandbox/DD4235/Military Decorations|makeTemplate|...}}
to see what I mean. — Mr. Stradivarius ♪ talk ♪ 07:01, 21 April 2014 (UTC)- Thanks. I'll try both of those solutions. I didn't realize that modules could be substituted.DD4235 (talk) 02:38, 23 April 2014 (UTC)
- Frame:preprocess() which is generally deprecated as a slow solution, but has the advantage that it works on pretty much any wikitext without having to think about the specific syntax. You can refine processing of the individual items later on as you see fit. Wnt (talk) 01:31, 25 April 2014 (UTC)
- Thanks. I'll try both of those solutions. I didn't realize that modules could be substituted.DD4235 (talk) 02:38, 23 April 2014 (UTC)
- Having said that, substituting the module should work without using frame:expandTemplate, as substitution happens at an earlier stage of processing. Try using
Working across multiple languages
I am working on a template that I'd like to be able to move into other language wikipedias with the minimum of recoding. A fragment of the English template looks like this:
{{{2|{{Title without disambig|{{PAGENAME}}}}}}}
In French this becomes:
{{{2|{{Titre sans précision|{{PAGENAME}}}}}}}
What I would really like to do is invoke the relevent code of {{Title without disambig}} directly in-line, ie without having to name it. Partly this is because that template does not even exist in some languages, eg German (Maltese etc), but also because it is implemented in different ways.
it:Template:Pipetrick {{safesubst:#if:{{{2|}}}|{{{2}}}|{{safesubst:Str prima|{{safesubst:#if:{{{1|}}}|{{{1}}}|{{safesubst:PAGENAME}}}}| (}}}}
fr:Modèle:Titre sans précision {{#Invoke:String|simpletitle|{{#if:{{{1|}}}|{{{1}}}|{{FULLPAGENAME}}}}}}
es:Plantilla:Título sin coletilla {{#Invoke:String|replace|{{{1|}}}|%s%(.*%)||plain=false}}
Lua certainly looks like a promising direction. So, to cut out the 'external' template invocation for consistency and for transportability reasons, what should my first code fragment look like if I use Lua? and will Lua work on every single language Wikipedia? Thanks! Scarabocchio (talk) 09:06, 26 April 2014 (UTC)
- Sometimes you re-read a posted question and the answer just jumps out at you
- {{#Invoke:String|replace|{{{2|{{FULLPAGENAME}}}}}|%s%(.*%)||plain=false}}
- Will this work on all language Wikipedias? Scarabocchio (talk) 09:13, 26 April 2014 (UTC)
- I would put all of your code in a Lua module to start with. Then I would implement {{Title without disambig}} as a function in the Lua module, so that it is guaranteed to be the same in each wiki. Then you can just call that function instead of trying to find the proper template name, as the template may or may not exist, and if it exists it may or may not do what you want. What your first code fragment should look like depends on what you want your code to do. So we would need to know more about the specifics of your situation before we can give you a good answer. And yes, Lua will work on every language Wikipedia - and even Wikimedia wikis that aren't Wikipedias. :) — Mr. Stradivarius ♪ talk ♪ 09:21, 26 April 2014 (UTC)
- Also, the code in your second post will work if every wiki uses the same version of Module:String. They probably do, but it's not guaranteed. And a better Lua pattern to use would be {{#invoke:string|replace|{{{2|{{FULLPAGENAME}}}}}|%s*%(.-%)$||plain=false}}. That is anchored to the end of the title, whereas yours might match something in the middle. And yours would match more than one set of brackets, if there are more than one for some reason. — Mr. Stradivarius ♪ talk ♪ 09:29, 26 April 2014 (UTC)
- Many thanks! Scarabocchio (talk) 10:04, 26 April 2014 (UTC)
FYI. Your {{#invoke:string|replace|{{{2|{{FULLPAGENAME}}}}}|%s*%(.-%)$||plain=false}} doesn't work in French WP (though it does work in enWP). The variant that I gave in my second message (lifted from {{Title without disambig}}) happens to work in both, but presumably this is also fragile with respect to further languages. (See https://fr.wikipedia.org/wiki/Utilisateur:Scarabocchio/Tester if you want to check the above statement). I'll use 'my' variant for the time being, and in any case will check all parameter combinations in each language I add the template to. Scarabocchio (talk) 11:51, 26 April 2014 (UTC)
- Ignore that! I hadn't stripped the trailing spaces off the positional parameter, so the anchored regexp comparison failed, while the unanchored one "worked". Apologies. Scarabocchio (talk) 10:47, 27 April 2014 (UTC)
Module:it-conj
Could someone make that Module:it-conj in Wiktionary gives every page which uses any third parameter (e.g. leggere) the Category Italian irregular verbs? Compare this discussion. Thank you --Bigbossfarin (talk) 19:54, 3 July 2014 (UTC)
- @Bigbossfarin: I'm not totally sure what you're asking for, but would
if args[3] and mw.text.trim(args[3]) ~= '' then
table.insert(data.categories, 'Italian irregular verbs')
end
- work? Jackmcbarn (talk) 20:23, 3 July 2014 (UTC)
- Thank you for you help Jackmcbarn, but I think that doesn't work if any special parameter like "pastp=letto" appears. Is there any way to make that any additional parameter is filtered by this category?--Bigbossfarin (talk) 23:23, 4 July 2014 (UTC)
- @Bigbossfarin: What about this?
- Thank you for you help Jackmcbarn, but I think that doesn't work if any special parameter like "pastp=letto" appears. Is there any way to make that any additional parameter is filtered by this category?--Bigbossfarin (talk) 23:23, 4 July 2014 (UTC)
for k,v in pairs(args) do
if k ~= 1 and k ~= 2 and mw.text.trim(v) ~= '' then
table.insert(data.categories, 'Italian irregular verbs')
break
end
end
- Jackmcbarn (talk) 23:48, 4 July 2014 (UTC)
- Thank you I will try it! --Bigbossfarin (talk) 12:25, 5 July 2014 (UTC)
- It works! Thank you you very much for your help --Bigbossfarin (talk) 12:38, 5 July 2014 (UTC)
- Jackmcbarn (talk) 23:48, 4 July 2014 (UTC)
Module:Infobox NCAA team season
I'd like to talk about replacing {{Infobox NCAA team season}} with a proper LUA module. I feel a little like a tail wagging a dog, because my main concern is how kludgy the process is to identify whether the season name should include "Men's", Women's" or neither (which is not as simple as it might sound. For example, the recent Arkansas men's basketball team title should be "2013–14 Arkansas Razorbacks men's basketball team" but the Central Arkansas title should be "2013–14 Central Arkansas Bears basketball team".)
I note that the existing templates use a lot of switching to deal with the fact that they are covering six sports. Would it make sense to have a different version of each module for each sport? I'm thinking yes, but I'll defer to those with more expertise. If the answer is yes, the obvious question is whether to further subdivide between sex? I'm thinking no, but again, will defer to experts. Even if it makes sense to have nine separate modules, several still need to identify whether "Men's", Women's" or neither should be included, but I think that can be done simply, by having a sex parameter allowing "none" as a variable. (Unless that parameter drives anything else, in which case we need a second parameter, such as sextitle.)
What can I do to help write specs?
FYI, this template has 8296 transclusions.--S Philbrick(Talk) 21:55, 14 July 2014 (UTC)
- This looks like a good candidate for Lua conversion. However, I'm a little reluctant to convert infoboxes to Lua right now, as once mw:Extension:Capiunto is released we will have to redo them. I suppose I should try and contribute to the Capiunto code myself to speed things along - it's been being written for quite a while now. — Mr. Stradivarius on tour ♪ talk ♪ 08:04, 23 July 2014 (UTC)
We need a simple, straightforward, Wiki-wide syntax to put a mark on a damn map. (Aside from raw html/css that is)
I was just appalled by a situation with July 2014 Al-Wadi Al-Gedid attack, where the editors had put in an image coloring the entire province after some militants massacred people at a border checkpoint with Libya. The item was profiled site-wide from "In the news", and I feel like by coloring this in, we distracted from the actual coordinates it occurred at rather than highlighting them, and gave the militants an unwanted little boost by making it look like they control a huge chunk of Egypt.
The root of it is that Template:Infobox military conflict has some byzantine syntax required to use a location map, referring to the documentation of other templates to explain its own documentation, and at least in any short period of time I can't figure out how to put a mark on it. Judging by a dozen battles I picked out, nobody else seems to know either, because none use the feature. It's impossible to simply import a map from, say, Farafra, Egypt and move the mark, because Template:Infobox settlement uses a whole different set of parameters. Now I realize that in the end we can just go with Template:Location map and try to ignore the rest, or better yet, just set up a div and set the mark about where it looks right ... but what we want really is a standard interface. I see that Module:Location map has made some heroic strides in this direction e.g. Module:Location map/data/Abkhazia (unfortunately we don't have one for Egypt, which may be part of the problem). But I'm thinking maybe what we really need is some way to make things more modular overall, i.e. a standard parameter that allows you to pass in the entire innards of the image frame preformatted, whether by transclusion or by calling another template etc., that bypasses more specialized (and variable) syntax. Maybe not - my thinking on this is admittedly confused, and I'm sure some here have tackled these situations often. But I want someone to come up with some kind of general philosophy to organize the approach rather than just diving in and making yet another divergent template or module. Wnt (talk) 15:43, 22 July 2014 (UTC)
National football team rankings
Updating rankings on individual national football team articles has become an overly tedious task and I think it would be easier if {{Infobox national football team}} drew rankings from a single module and returned them on individual articles depending on the infobox's |Name=
parameter (the value given in the parameter is always the same as "[name] national football team" in the article's title). Users, preferably members of the national teams task force, can then update these rankings every time new revisions are released. There should be a separate list for women's national teams, which would return rankings if |type=women
in the infobox is active.
So basically, one central module should pull data from separate lists containing men's and women's rankings. For men, there should be two lists for FIFA World Rankings and World Football Elo Ratings, and for women one list containing FIFA Women's World Rankings. Davykamanzi → talk • contribs • alter ego 04:28, 23 July 2014 (UTC)
- It would be bad for the job queue to have all soccer pages pull rankings from the same page. Jackmcbarn (talk) 04:33, 23 July 2014 (UTC)
- With only 1237 articles using {{Infobox national football team}}, it wouldn't be that bad on the job queue. Another option though might be a wikidata item. Would still mean having to update a number of pages, but the rankings could then be used over all languages. Another thought is that the rankings could be done with a normal template #switch statement rather than needing to use lua and just placed as subpages of the template. -- WOSlinker (talk) 07:08, 23 July 2014 (UTC)
- It can quite easily be done on different subpages in Lua as well. Storing the data in Wikidata sounds like the best idea to me, though. — Mr. Stradivarius on tour ♪ talk ♪ 07:57, 23 July 2014 (UTC)
- Well, I'm absolutely stunned to see that a few days ago action was taken that might permit this to be possible (Bugzilla, merge) - still, my understanding is that Wikidata doesn't just let you add any old thing you want, everything takes approval. Also, I don't think it's live yet, because the examples from [5] (,) still don't produce any text. It would be a lot easier to do it with a WP based data file first, and then if someone cares he can look into coordinating the data files later. Wnt (talk) 13:28, 23 July 2014 (UTC)
- It can quite easily be done on different subpages in Lua as well. Storing the data in Wikidata sounds like the best idea to me, though. — Mr. Stradivarius on tour ♪ talk ♪ 07:57, 23 July 2014 (UTC)
- With only 1237 articles using {{Infobox national football team}}, it wouldn't be that bad on the job queue. Another option though might be a wikidata item. Would still mean having to update a number of pages, but the rankings could then be used over all languages. Another thought is that the rankings could be done with a normal template #switch statement rather than needing to use lua and just placed as subpages of the template. -- WOSlinker (talk) 07:08, 23 July 2014 (UTC)
- Some broader issues concern this. First, WP:NOTNEWS is usually misapplied in support of deleting anything that might compete with commercial news outlets, such as articles about recent events; but it actually does say that we shouldn't value the rankings for, say, July 17 more than we value those for some time in June. This is an encyclopedia and our goal isn't actually to produce continually-updated rankings. Also, there could be copyright issues over taking every single judgment call FIFA has ever made and putting it into a database. I ended up losing List of Forbes Global 2000 companies to such concerns and this seems pretty similar. So while we can write the module I don't know if you should really use it. Wnt (talk) 13:34, 23 July 2014 (UTC)
- @Wnt: The point isn't to produce continually-updated rankings. FIFA rankings are updated once every month or so anyway. Elo ratings however are updated almost everyday, but we could just update them the same time new FIFA rankings are released. Besides that I don't see how copyright issues would affect this. Davykamanzi → talk • contribs • alter ego 17:13, 23 July 2014 (UTC)
- Have you considered using the FIFA API (See PDF )? I am thinking someone could design a Wikidata standard for the necessary information, populate on regular intervals using the API, then populate Wikipedia articles with links to the Wikidata elements.--S Philbrick(Talk) 18:29, 23 July 2014 (UTC)
- @Wnt: The point isn't to produce continually-updated rankings. FIFA rankings are updated once every month or so anyway. Elo ratings however are updated almost everyday, but we could just update them the same time new FIFA rankings are released. Besides that I don't see how copyright issues would affect this. Davykamanzi → talk • contribs • alter ego 17:13, 23 July 2014 (UTC)
Lua library to implement Javascript regexes?
I just got a question about using the alternation operator from Javascript in a Module:Highlight I slapped together in a hurry in response to a VPT thread. It would be wonderful if someone could code up Lua functions that work like the present Lua regex functions, but using standard Javascript regexes. It seems possible (though probably a bit slow), and obvious enough that I shouldn't have to reinvent the wheel... I bet someone can point me right at a free-licensed library routine we can just out and out steal and be done with this. Wnt (talk) 01:57, 5 August 2014 (UTC)
- @Wnt: I can't find any such library, and the people in freenode #lua don't know of any either. I doubt one exists. (Note that there's plenty of libraries that call out to C functions to do it, but for MediaWiki we'd need one written in pure Lua.) Jackmcbarn (talk) 02:44, 5 August 2014 (UTC)
- Thanks for trying! I suppose the next question to ask is whether anyone has proposed some extended syntax for Lua to handle the Javascript-like features that it lacks. I'm thinking we'd want to first convert from Javascript syntax to Lua syntax - sometimes quite simply, /d to %d and such, but other times requiring new "Lua-like" syntax to deal with the extra features; then have a module that can deal with the extended syntax in a way that is hopefully fairly efficient. That way the same module could handle either the Javascript syntax or a Lua syntax with non-standard features almost exactly the same way. But without defining any new special characters for such regexes coming up with that syntax might be rather tricky. Certainly if anyone has proposed a standard for it already it would be best to stick by it. Wnt (talk) 08:25, 5 August 2014 (UTC)
- Well, since no one suggested a better idea, I'm thinking of something like the following adaptation scheme:
Javascript Lua extension (x|y) %e[x^y] n{X} %r[n^X] n{X,Y} %r[n^X^Y] n{X,} %r[n^X^] ?=n %g[n] ?!n %G[n] \ddd %j[ddd] \xdd %j[xdd] \udddd %j[udddd] . %j[.]
- Seems like %e, %r, %g, %n are apparently unused in patterns... I think. ^ already has meaning at the beginning of the string. %^ would still only be required in the abnormal %e text itself. This isn't complete (and I doubt the module would be any time soon either!), but the notion of unused %alphabeticals in patterns seems like the obvious expansion method. Wnt (talk) 23:40, 7 August 2014 (UTC)
- If you do want to go the route of implementing this yourself, there's already a pure-Lua implementation of Lua's own pattern matching at [6] that would probably be the best place to start. Jackmcbarn (talk) 23:45, 7 August 2014 (UTC)
Hi Jack ... this was my request, and it's been frustrating because it's necessary for my copyediting project (I can explain why if you like), and what I want is a tiny change, but I haven't been able to find help ... my bugzilla request has been assigned a "low" priority and has no takers. I know a little more now thx to Wnt: "I see ... some version (I don't know if it's the most recent for sure) of the highlightText at [7] with the infamous split-on-space at line 12." That's exactly it ... what I need is a function (in or outside of Mediawiki) identical to highlightText, with (I'm guessing) the space in pat.split(" ") in line 12 replaced ... a tab character would work. (Or, getting rid of the parsing entirely so I can pass an array of strings would be fine.) - Dank (push to talk) 17:22, 5 August 2014 (UTC)
- Dank, what bugzilla request? It's always helpful to link to such things using {{Bug|######}}, {{Bugzilla|######}}, {{Tracked|######}}, or [[:bugzilla:######]]. — {{U|Technical 13}} (e • t • c) 08:57, 9 August 2014 (UTC)
- T69784. - Dank (push to talk) 09:22, 9 August 2014 (UTC)
Module:Coordinates
Is someone willing/able to modify Module:Coordinates/sandbox so that it can import coordinates from Wikidata? Importing coordinates from Wikidata can be done with this syntax ({{#property:P625}}
) but its output is not formatted right to be accepted by this module. The functionality needs to be added so that we can import coordinates directly from Wikidata, using the {{Coord}} template maybe in this format: {{Coord|{{#property:P625}}|display=...}}
. Thanks. -- P 1 9 9 ✉ 16:57, 11 August 2014 (UTC)
- Using #property is waste of CPU cycles for useless formatting-parsing the coordinates. It is better to read the property value directly in lua module if the coordinates are not provided as argument of the template. Paweł Ziemian (talk) 21:44, 11 August 2014 (UTC)
- It was just a suggestion. If there is a better way, by all means! Use it instead. The key issue is to import coordinates directly from Wikidata to the {{coord}} template. -- P 1 9 9 ✉ 13:34, 12 August 2014 (UTC)
- @P 1 9 9: Allready done. If you have an coord template transclusion with no numbered arguments and there is an coordinate on the linked wikidata item the coordinate from wikidata will show up. See Module talk:Coordinates#This template doesn't support wikidata! for details. If you have any other problems with it, then please say so.--Snaevar (talk) 16:35, 15 September 2014 (UTC)
- Thank you very much. Can you update Template:Coord/doc to describe its features and use? -- P 1 9 9 ✉ 20:00, 15 September 2014 (UTC)
- Sure. Done.--Snaevar (talk) 12:41, 17 September 2014 (UTC)
- Thank you very much. Can you update Template:Coord/doc to describe its features and use? -- P 1 9 9 ✉ 20:00, 15 September 2014 (UTC)
Wikidata qualifier
Is someone willing/able to write a new module that can import qualifier statements from Wikidata? For example to use the "point in time" qualifier for population numbers. See also https://meta.wikimedia.org/w/index.php?title=Talk:Wikidata/Notes/Inclusion_syntax_v0.4#Accessing_qualifiers_for_statements. Thanks. -- P 1 9 9 ✉ 17:08, 11 August 2014 (UTC)
- @P199: Can you link to a page that has a data item with a qualifier? Jackmcbarn (talk) 00:57, 11 September 2014 (UTC)
- Sure. For instance, Zamboanga City. The Wikidata item has a "population" statement with the "point in time" and "determination method" qualifiers. I want to use the date in the "point in time" qualifier when importing the "population" number. This would be a huge help in keeping the data accurate. Thanks for looking into this. -- P 1 9 9 ✉ 01:34, 11 September 2014 (UTC)
- @P199: I updated Module:Wikidata to include qualifier variants of its 3 functions. They take the qualifier ID right after the property ID and otherwise work identically. Jackmcbarn (talk) 01:50, 11 September 2014 (UTC)
- Thanks for working on this. I tried it with the following syntax (
{{#invoke:Wikidata|getDateValue|p585|FETCH_WIKIDATA|dmy}}
) but didn't work. I don't think I have the right code, and it is not described on the documentation page. What is the right syntax for it? -- P 1 9 9 ✉ 13:36, 11 September 2014 (UTC)- @P199: The syntax in this case is
{{#invoke:Wikidata|getQualifierDateValue|P1082|P585|FETCH_WIKIDATA|dmy}}
. Jackmcbarn (talk) 13:59, 11 September 2014 (UTC)
- @P199: The syntax in this case is
- Great! Thank you very much. One more idea: can you provide more date output formats, like year only? -- P 1 9 9 ✉ 15:19, 11 September 2014 (UTC)
- Thanks for working on this. I tried it with the following syntax (
- Sure. For instance, Zamboanga City. The Wikidata item has a "population" statement with the "point in time" and "determination method" qualifiers. I want to use the date in the "point in time" qualifier when importing the "population" number. This would be a huge help in keeping the data accurate. Thanks for looking into this. -- P 1 9 9 ✉ 01:34, 11 September 2014 (UTC)
@Jackmcbarn: Can you provide more date output formats, like year only? Notice at Othón P. Blanco, Quintana Roo, that "1 January" is added while Wikidata only has the year as qualifier. Thanks. -- P 1 9 9 ✉ 18:00, 7 October 2014 (UTC)
- Nevermind. I already did it. -- P 1 9 9 ✉ 16:52, 9 October 2014 (UTC)
overhaul Module:Chart
(reference, Module talk:Chart#Line chart option)
so, Module:Chart has two main functions, bar chart and pie chart.
i do not know of a better way to do pie charts, so forget about it for a moment. bar chart works by creaing raw html/css entities (mainly divs, but also textual legends)) and do all kinds of gymnastics to do it right, by setting style options for location, color and size of the elements. this is not good, we should really use mw:Extension:Timeline to render the chart. timeline syntax may not be trivial, and this is where lua should be used.
so here is the challenge,
- look at Module:Chart - not so much the actual code - look at the "syntax", in the documentation and examples.
- if yo like the syntax, think of ways to make it better: easier to use, more powerful, cleaner, etc.
- if you do not like the syntax, try to come up with a better one
- learn the timeline extension syntax
- create a module that generates line chart, vertical bar chart (both "stacked" and "traditional"), and horizontal bar charts (probably "stacked" only for h-bar), using unified syntax. ideally, one will be able to switch between line, v-bar, stacked v-bar and h-bar, simply by changing a single parameter: all the data, legends, links, colors, etc. should still work for all types. utilize as much or as little from Module:Chart code as makes sense: the rendering code is junk, but (depending on the syntax chosen), some of the logic used to process the parameters may be useful
- ideally, it should be simple to use data sources, e.g., one could feed information to Module:Chart by copy-pasting CSV data, and choosing comma as the "delimiter"
- create some nice, easy to use, specific templates (using this module) for each individual chart type
- advertise it better than i did with Module:Chart and better than the authors of Template:Line chart did with that template.
we have a very impressive template called Template:Line chart (copied from french wikipedia fr:Template:Graphique polygonal) which utilizes the easytimeline extension, but because of templating limitations (which Lua solves), it is cumbersome to use, and the template source code itself is practically unreadable and unmaintainable.
for instance, look at the nice graph in The Legend of Korra, the graph code is copied here:
{{Line chart | color_background = white | width = 600 | height = 350 | padding_left = 40 | padding_right = 15 | padding_top = 10 | padding_bottom = 20 | number_of_series = 2 | number_of_x-values = 11 | label_x1 = Ep. 1/2 | label_x2 = Ep. 3 | label_x3 = Ep. 4 | label_x4 = Ep. 5 | label_x5 = Ep. 6 | label_x6 = Ep. 7 | label_x7 = Ep. 8 | label_x8 = Ep. 9 | label_x9 = Ep. 10 | label_x10 = Ep. 11/12 | label_x11 = Ep. 13/14 | y_max = 5000 | scale = yes | points = yes | color_series_1 = blue | color_series_2 = black | thickness_series1 = 1 | thickness_series2 = 1 | S01V01 = 4550 | S01V02 = 3550 | S01V03 = 4080 | S01V04 = 3780 | S01V05 = 3880 | S01V06 = 3450 | S01V07 = 2980 | S01V08 = 3580 | S01V09 = 3540 | S01V10 = 3680 | S02V01 = 2600 | S02V02 = 2190 | S02V03 = 2380 | S02V04 = 1100 | S02V05 = 1950 | S02V06 = 1730 | S02V07 = 1730 | S02V08 = 2470 | S02V09 = 2220 | S02V10 = 1870 | S02V11 = 2090 | }}
(i added some line breaks to make it easier to read as "pre" because pre does not do line wrap)
compare with something like:
{{Line chart | color_background = white | width = 600 | height = 350 | padding_left = 40 | padding_right = 15 | padding_top = 10 | padding_bottom = 20 | delimiter = , | x-labels = Ep. 1/2 , Ep. 3 , Ep. 4 , Ep. 5 , Ep. 6 , Ep. 7 , Ep. 8 , Ep. 9 , Ep. 10 , Ep. 11/12 , Ep. 13/14 | scale = yes | points = yes | colors = blue , black | group names = Book One: "Air" (2012) , Book Two: "Spirits" (2013) | thickness = 1 , 1 | group 1 = 4550 , 3550 , 4080 , 3780 , 3880 , 3450 , 2980 , 3580 , 3540 , 3680 | group 2 = 2600 , 2190 , 2380 , 1100 , 1950 , 1730 , 1730 , 2470 , 2220 , 1870 , 2090 }}
now, the difference may not seem dramatic, but imaging adding 4 more data-series: with the "S03V11" notation this is tedious and error prone, and with the 2nd format this can be copied as-is from same data source that uses CSV (export directly from excel).
TLDR
Challenge:
- convert the bar graphs in Module:Chart to use the timeline extension, possibly while improving the module syntax, add line-chart and horizontal bar-chart options, all with unified syntax.
- as much as possible, continue supporting the useful stuff in current module, such as hot-links and useful tooltip for individual bars, allow multiple axes, etc.
- create individual easy to use templates for each chart type (vertical bar chart, stacked v-bar, h-bar, line chart)
peace - קיפודנחש (aka kipod) (talk) 22:54, 22 September 2014 (UTC)
- I wonder what the chances are of getting mw:Extension:Graph enabled. Anomie⚔ 10:25, 23 September 2014 (UTC)
- I note that extension doesn't work at all without JavaScript. Jackmcbarn (talk) 20:06, 23 September 2014 (UTC)
- @Anomie: instead of going with old abandonware, i'd much rather have some way to utilize inline-svg: i do not see any advantage to JS-dependant canvas which this extension uses. if we go the JS route, i'd rather use something nice and "standard" (and maintained) like Raphaël.
- however, since you mentioned the "Graph" extension: seeing that this extension expects input using JSON serialization, what do you think about adding json support to scribunto? would be nice to be able to serialize and deserialize lua object to json and vice versa, and i'm sure it will be useful elsewhere. peace - קיפודנחש (aka kipod) (talk) 23:31, 23 September 2014 (UTC)
- @קיפודנחש: See bugzilla:45470 for JSON support. I don't see JSON as being very useful in this particular case, though. Much more useful would be the ability to just emit SVG text from Scribunto, which bugzilla:64460 is about. Jackmcbarn (talk) 23:40, 23 September 2014 (UTC)
- @קיפודנחש: There's a new "Extension:Graph" replacing the abandonware one. Or is "abandonware" referring to something used in the extension?
- But that it doesn't work without JS is problematic (thanks Jackmcbarn for pointing that out). I filed T73227, and I agree that without a reasonable fix there Graph isn't ready for use at all.
- As for bugzilla:45470, I'm thinking we're going to have to do that with the rise in stuff like mw:Extension:JsonConfig. Anomie⚔ 10:20, 24 September 2014 (UTC)
- bottom line: some way to use scribunto to generate and display inline-svg seems to be the best way to do things long-term.
- however, for the medium and short term, i'd still like to see either Module:Chart converted to use easytimeline for the bar chart, or a new module making easytimeline use easy and convenient written. i outlined above how i see it, but it will be even better if other people suggest improvements to the syntax, or better syntax altogether. i will not have time in the near future to do the actual coding myself, and i sure hope someone else will. peace - קיפודנחש (aka kipod) (talk) 13:19, 24 September 2014 (UTC)
- I note that extension doesn't work at all without JavaScript. Jackmcbarn (talk) 20:06, 23 September 2014 (UTC)
Fork Infobox drugs
Can somebody set up a Lua-fork of Template:Infobox_drug for me at e.g. Template:Infobox_drug/Lua-fork? I don't need the whole box, just the basic set up for a Wikidata-infobox and maybe one property as an example so I can work from there. I couldn't find a how-to guide for converting an infobox into Lua, but will volunteer to write a step-by-step guide as I go along for other people that are interested in this. --Tobias1984 (talk) 22:24, 20 October 2014 (UTC)
- Forks are a terrible idea. Why not just rewrite the real template to use Lua? Jackmcbarn (talk) 22:52, 20 October 2014 (UTC)
- @Jackmcbarn: I would like to experiment with a new layout and put it up for discussion if it should be implemented. Do you think that I should just modify the current Infobox code in a separate place? -Tobias1984 (talk) 23:22, 20 October 2014 (UTC)
- The proper place to do that is in Template:Infobox drug/sandbox. Jackmcbarn (talk) 23:35, 20 October 2014 (UTC)
- I made my a sandbox page now at Template:Infobox_drug/sandbox3 and informed WikiProject Pharmacology. I am testing the infobox here: User:Tobias1984/Infobox drug test Is there any way to pretend-connect the page with the WD-item for Warfarin, so I don't see the template error? -Tobias1984 (talk) 12:02, 21 October 2014 (UTC)
- The proper place to do that is in Template:Infobox drug/sandbox. Jackmcbarn (talk) 23:35, 20 October 2014 (UTC)
- @Jackmcbarn: I would like to experiment with a new layout and put it up for discussion if it should be implemented. Do you think that I should just modify the current Infobox code in a separate place? -Tobias1984 (talk) 23:22, 20 October 2014 (UTC)
- I'm going to move this question to Module talk:Wikidata where it might be more appropriate. -Tobias1984 (talk) 09:42, 22 October 2014 (UTC)
Creating new template parameters with Lua
I am trying to use a Lua module to create template parameters. What I would like to do is to parse the value of a single parameter to produce several new parameter/value pairs. The template in question is {{Vcite2 journal}} in which I invoke Module:ParseVauthors. I would like the module to parse a comma delimited list stored in |vauthors=
and return one or more |authorn=
.
The following is a test case:
- {{vcite2 journal | vauthors = Bannen RM, Suresh V, Phillips GN, Wright SJ, Mitchell J | year = 2008 | title = Optimal design of thermally stable proteins | url = http://bioinformatics.oxfordjournals.org/cgi/content/full/24/20/2339 | journal = Bioinformatics | volume = 24 | issue = 20 | pages = 2339–43 | doi = 10.1093/bioinformatics/btn450 | pmc = 2562006 | pmid = 18723523 }} →
- Bannen RM, Suresh V, Phillips GJ, Wright SJ, Mitchell J (2008). "Optimal design of thermally stable proteins". Bioinformatics. 24 (20): 2339–43. doi:10.1093/bioinformatics/btn450. PMC 2562006. PMID 18723523.
Obviously Module:ParseVauthors is not working because the author list is blank in the rendered citation (apparently author1 = Bannen RM, author2 = Suresh V, author3 = Phillips GN, author4 = Wright SJ, author5 = Mitchell J are not being generated). Note: the "Unknown parameter" is a separate problem (somehow I need to "destroy" |vauthors=
after it is parsed).
Suggestions on how to get this to work would be most appreciated. Boghog (talk) 14:53, 2 November 2014 (UTC)
- @Boghog: I see that you're trying to pass things to the template by using
_G["author"..i]=myTable[i]
, but that won't work, as _G doesn't have anything to do with the template. _G is a table containing all the global variables available to the module, but the template arguments are contained in frame objects. And you can only read template arguments in a frame object, you can't write to them. (Well, you can overwrite them, but that only affects the table in the Lua module, it doesn't affect the actual template.) To access a template from Lua you need to use frame:expandTemplate, or perhaps frame:preprocess depending on the situation. Also, there are a few differences between standard Lua 5.1 and the Lua 5.1 that is used in Scribunto; for your module, this means that the print function won't work. You need to use return values instead. Also, it means that your string:split function won't work as intended, as the string table available to modules is a copy of the string table available to strings. E.g.:
function string.foo ()
return 'Hello!'
end
local s = 'I am a string.'
-- This will log 'Hello!' to the console:
mw.log(string.foo(s))
-- This will produce an error "attempt to call method 'foo' (a nil value)."
mw.log(s:foo())
- However, in this case there is already a function in the text library for splitting strings - see mw.text.split. Hope this helps, and if you have any more questions, don't hesitate to ask. Best — Mr. Stradivarius ♪ talk ♪ 15:29, 2 November 2014 (UTC)
- @Boghog: I thought showing you the sort of thing that needed to be done might be quickest, so I've made some updates to Module:ParseVauthors and Template:Vcite2 journal for you. — Mr. Stradivarius ♪ talk ♪ 16:28, 2 November 2014 (UTC)
- @Mr. Stradivarius: Fantastic! Your clear explanation and extremely helpful edits to the module and template so that they work as I had intended are greatly appreciated. Cheers. Boghog (talk) 18:13, 2 November 2014 (UTC)
- @Boghog: I thought showing you the sort of thing that needed to be done might be quickest, so I've made some updates to Module:ParseVauthors and Template:Vcite2 journal for you. — Mr. Stradivarius ♪ talk ♪ 16:28, 2 November 2014 (UTC)
New entry for module:infobox
About module Infobox (edit · talk · history · links · /subpages · /doc · /doc edit · /sbox · /sbox diff · /test · Template:infobox) .
At the template talkpage, there was was a request to add parameter |subtitle=
. After a sidetracking, I refocused the discussion. Can someone write the Lua code for this entry, say in the sandbox? It should take semantics into consideration. I made a few simple suggestions there. -DePiep (talk) 10:11, 3 November 2014 (UTC)
My getArgs disappears the first unnamed 1= argument
I am researching module:Arguments to get learn it. Now, when I echo my input arguments (getArgs), there is this:
- {{#invoke:User:DePiep/cc|echo|foo|bar}} → #1: foo, #2: bar
- {{#invoke:User:DePiep/cc|echo|1=foo|bar}} → #1: bar
(More code or proof needed?) In test 2 the first parameter has is not seen. Any hints?. -DePiep (talk) 22:56, 10 November 2014 (UTC)
- That's nothing to do with Lua, it's just the way {{...}} works. I believe the text is parsed left-to-right although I don't recall seeing that in any docs. When "1=foo" is encountered, it sets the first unnamed argument to "foo". When "bar" is encountered, it sets the first unnamed argument to "bar" (which replaces "foo"). After that, the result is passed to #invoke, which calls the module. All templates and module invokes do that. Johnuniq (talk) 23:09, 10 November 2014 (UTC)
- Wow, you're right. It goes wrong in full wikicode too. I have never met this in old wikicode age (knowingly ...). -DePiep (talk) 23:25, 10 November 2014 (UTC)
- And there is a plenty of such incorrect usages, which are tracked by the Category:Pages using duplicate arguments in template calls. Paweł Ziemian (talk) 21:41, 11 November 2014 (UTC)
- Wow, you're right. It goes wrong in full wikicode too. I have never met this in old wikicode age (knowingly ...). -DePiep (talk) 23:25, 10 November 2014 (UTC)
Help fix Script error on Telugu WP Templates which are imported from English WP
https://te.wikipedia.org/w/index.php?title=Template:Yesno&oldid=1405292 Template page shows error "Script error: Lua error at line 1: unexpected symbol near '{'" and displays the template script, which is usually not shown. Similarly https://te.wikipedia.org/w/index.php?title=Template:Category_handler also shows same error, probably related to Documentation. --Arjunaraoc (talk) 01:42, 10 February 2015 (UTC)
- @Arjunaraoc: You somehow imported our template as a module. Re-import the template as the template and the module as the module, deleting what's already there if necessary. Jackmcbarn (talk) 03:10, 10 February 2015 (UTC)
- Thanks Jackmcbarn for your response. Your suggestion worked. --Arjunaraoc (talk) 08:09, 10 February 2015 (UTC)
orginal | alias |
---|---|
EpisodeNumber | 에피소드 번호 |
EpisodeNumber2 | 에피소드 번호 2 |
Title | 제목 |
RTitle | 제목 주석 |
AltTitle | 부제 |
RAltTitle | 부제 주석 |
Aux1 | 예비1 |
DirectedBy | 감독 |
WrittenBy | 각본 |
Aux2 | 예비2 |
Aux3 | 예비3 |
OriginalAirDate | 본방송일자 |
AltDate | 방송일자 2 |
ProdCode | 작품번호 |
Viewers | 시청률 |
Aux4 | 예비4 |
ShortSummary | 요약 |
LineColor | 선색 |
TopColor | 윗색 |
RowColor | 열색 |
Hello, I'm from Korean Wikipedia. I'd like to make a alias parameter(i.e. Korean parameter name) on my kowiki but I don't know how to do it. I need some help.--Namoroka (talk) 05:09, 15 February 2015 (UTC)
- I might be able to help if you can give a clear example of what currently works, and something which does not work now, but which you want. On a talk or sandbox page at kowiki would be fine. By example, I mean a template or whatever that calls the module, preferably with a brief description of what it does.
- Oh. Editing the wikitext to post my comment revealed the table at the side, tucked under the archive box. This looks simple, I think, but I still want examples because looking at code without knowing how it is called is a waste of time. Johnuniq (talk) 06:16, 15 February 2015 (UTC)
- I copied Module:Episode list to here and it works well in English(original) parameters. So I'd like to translate English parameter names into Korean names.--Namoroka (talk) 07:20, 15 February 2015 (UTC)
- I edited ko:Module:Episode list to include the aliases you gave. Please check them carefully because I just did a quick copy/paste from the displayed html, and that sometimes corrupts characters. You should now be able to use either enwiki or kowiki argument names; if both are given, the kowiki value will be used. See my comment about _mod. It probably does not matter, but I used Lua's mod function because ko:Module:Math is out of date and does not include _mod. I can't resist fiddling a little when editing code, but I only did that on stuff I had to change anyway. I kept all the enwiki names in the module and I suggest you do not try to change that because in the future people will probably want to compare the enwiki and kowiki versions to see if updates are needed, and that will be a lot easier if changes are kept to a minimum. You don't have to translate "Module" and you could restore them. Johnuniq (talk) 09:21, 15 February 2015 (UTC)
- By the way, in case it's not obvious, I have not tested the code and have no idea if it works! Let me know what a thorough test shows. Johnuniq (talk) 09:26, 15 February 2015 (UTC)
- It works gretly in both English and Korean. Thank you very much indeed! I will update ko:Module:Math soon. Thank you once again.--Namoroka (talk) 09:39, 15 February 2015 (UTC)
- I copied Module:Episode list to here and it works well in English(original) parameters. So I'd like to translate English parameter names into Korean names.--Namoroka (talk) 07:20, 15 February 2015 (UTC)
On reflection, what I put in the module is theoretically broken because it only captures expected arguments, namely those listed in the aliases table. If any other arguments, such as an unnamed argument, were used, they would be omitted. I don't think that would be a problem with this module, but following is what I think would fix it (again, very untested).
local aliases = {
['에피소드 번호'] = 'EpisodeNumber',
['에피소드 번호 2'] = 'EpisodeNumber2',
['제목'] = 'Title',
['제목 주석'] = 'RTitle',
['부제'] = 'AltTitle',
['부제 주석'] = 'RAltTitle',
['예비1'] = 'Aux1',
['감독'] = 'DirectedBy',
['각본'] = 'WrittenBy',
['예비2'] = 'Aux2',
['예비3'] = 'Aux3',
['본방송일자'] = 'OriginalAirDate',
['방송일자 2'] = 'AltDate',
['작품번호'] = 'ProdCode',
['시청률'] = 'Viewers',
['예비4'] = 'Aux4',
['요약'] = 'ShortSummary',
['선색'] = 'LineColor',
['윗색'] = 'TopColor',
['열색'] = 'RowColor',
}
local function local_args(args)
-- Return a new table of arguments using any given local options.
local result = {}
for k, v in pairs(args) do
result[aliases[k] or k] = v
end
return result
end
The above operates differently from my previous effort: if both enwiki and kowiki names are given for a particular argument, the result is undefined (either the enwiki or the kowiki value will be used, but it might be either). That situation should never arise so is not a concern.
Module:Episode list has a slight misunderstanding: it refers to args['1']
but that should never occur—the module should be using args[1]
for the first unnamed argument. Therefore, I don't think the above fix would achieve anything, but I'm mentioning it in case anyone else wants to look at the code for other places. Johnuniq (talk) 22:28, 15 February 2015 (UTC)
- There was something wrong with previous code. When {{Episode list/sublist}} is transcluded onto the main list, all
|ShortSummary=
s should be hided, but it doesn't work on kowiki. Now I replacedargs['1']
withargs[1]
, and it works well. Thank you.--Namoroka (talk) 09:45, 17 February 2015 (UTC)
Localizing Citation Module - Tewiki
I am trying to localize Citation Module to accept months written in Telugu Wikipedia. I have added Telugu month names to list in , but it is still giving date error, when Telugu month names are used. Any help is appreciated --వైజాసత్య (talk) 04:51, 8 March 2015 (UTC)
- That's a job for Trappist the monk. Meanwhile, please spell out what page you have edited that has a problem. Is it te:Module:Citation/CS1 or one of the others? Do you have a sandbox page for testing that has an example of a citation with a Telugu date, and which currently does not work? Johnuniq (talk) 06:41, 8 March 2015 (UTC)
- The most likely reason for an error message is because in function
check_date()
, the date format is validated by a series of pattern matches that expect ascii characters. Because Telugu is unicode, thestring.match()
tests fail when they encounter unicode characters.
- At ml:Module:Citation/CS1/Date validation, they added tests to
check_date()
for the date formats that use Malayalam months:mw.ustring.match(date_string, "^%d%d? [%C%D%P%W]+ %d%d%d%d?$")
- You might see if something like their solution will work for you.
- —Trappist the monk (talk) 14:02, 8 March 2015 (UTC)
- Thank you Trappist the monk, that solved the problem. Thanks Johnuniq for responding --వైజాసత్య (talk) 20:24, 8 March 2015 (UTC)
What I am after is Lua coding to recognize when a particular parameter is two characters or less and to top it up with 0s. The latter 'topping-up' part I can do, but it is a length-check I'm after.
- If 1 is inputted, it should be topped up to 001.
- If 93 is inputted, it should be topped up to 093.
- If C1 is inputted, it should be topped up to C01.
Basically I'm after a way of checking the number of characters in a string and then how to display a particular character so I can, if necessary, drop the 0 in the middle.--Launchballer 11:37, 18 March 2015 (UTC)
- Module:String#len?
{{#invoke:String|len|1}}
→ 1{{#invoke:String|len|93}}
→ 2{{#invoke:String|len|C1}}
→ 2
- —Trappist the monk (talk) 11:54, 18 March 2015 (UTC)
- To add zeros to the left of a string, you can use the {{padleft:}} magic word. This doesn't add them to the right of any letters, though.
{{padleft:1|3|0}}
→ 001{{padleft:93|3|0}}
→ 093{{padleft:C1|3|0}}
→ 0C1
- SiBr4 (talk) 12:06, 18 March 2015 (UTC)
- let's say you parameters are called P (input string) and L for length (i.e., {{{P}}}), and {{{L}}} ).
- wrinting it straight in lua is relatively easy. it looks, more or less, like so:
function padmiddle( source, len )
local nodigits = ustring.match( source, "^%D*" )
, digits = ustring.match( source, "%d*$" )
, padlen = len - ustring.len( source )
, zero = mw.language:formatNum( 0 )
return nodigits .. string.rep( zero, len ) .. digits
end
- this simplistic function does not verify correct input, so calling it with, say, ("11cc", 5), will return "0" (no non-digit at the beginning and no digits at the end: theoretically it should return "00000", but it assumes, naively, that the input is correct, so seeing 4 characters, it only uses a single 0 for padding)
- you can use existing functions to do it with no new lua code, like so:
{{#invoke:String|match|{{{P}}}|^%D*}}{{#invoke|string|rep|0|{{#expr:{{{L}}}-{{strlen|{{{P}}}}}}}}}{{#invoke:string|match|{{{P}}}|%d*$}}
- admittedly it's ugly, but i believe it should work (again - no sanity check for the correct form of input string). peace - קיפודנחש (aka kipod) (talk) 01:07, 19 March 2015 (UTC)
- Okay, and how do I get it to pick out a particular character from within the parameter, and recognize whether it is a letter or a number?
- admittedly it's ugly, but i believe it should work (again - no sanity check for the correct form of input string). peace - קיפודנחש (aka kipod) (talk) 01:07, 19 March 2015 (UTC)
--Launchballer 02:00, 19 March 2015 (UTC)
- you do not have to worry about "letter or number" - the "match" function with the correct patterns ("^%D*" for initial non-digits and "%d*$" for terminating digits) takes care of that. in the example above, {{{P}}} represents the input string, and {{{L}}} represents the desired length. if, in your case, if it's always 3, you can replace {{{L}}} in the example with 3. in the general case, i thought it's better to leave it as a parameter. note that {{{P}}} appears several times - you should replace them all with the correct parameter name. alternatively, you can create a new template containing the code above, and pass to it these two params. i want to make one point again: this code does not check for the validity of the input: it assumes that you supply it with a string that contains zero or more non-digit characters, and then zero or more consecutive digits. it should handle your examples above the way you required, but if you pass something like "1C" and length 3, you will get "0" (no non-digits at the beginning and no digits at the end, so all is left is the padding, which only take into account the total length, i.e., 3-2). peace - קיפודנחש (aka kipod) (talk) 12:41, 19 March 2015 (UTC)
- @Launchballer: - just curious: did you find the above useful ?
- peace - קיפודנחש (aka kipod) (talk) 15:44, 21 March 2015 (UTC)
- קיפודנחש: Just tested it at User talk:Launchballer/sandbox. The Lua is used in the URL "Full timetable (PDF)" and a category, both of which seem to be broken.--Launchballer 11:50, 23 March 2015 (UTC)
- @Launchballer: yes, the code above contained a bug: it had "#invoke|string" instead of "#invoke:String". i fixed it when testing, but forgot to fix it in my message... sorry about that. to make life tiny bit easier, i created Template:Zpadmiddle ("pad middle of string with zeroes"). if you do not find it useful, please mark it for deletion. peace - קיפודנחש (aka kipod) (talk) 16:02, 24 March 2015 (UTC)
- קיפודנחש: Just tested it at User talk:Launchballer/sandbox. The Lua is used in the URL "Full timetable (PDF)" and a category, both of which seem to be broken.--Launchballer 11:50, 23 March 2015 (UTC)
- you do not have to worry about "letter or number" - the "match" function with the correct patterns ("^%D*" for initial non-digits and "%d*$" for terminating digits) takes care of that. in the example above, {{{P}}} represents the input string, and {{{L}}} represents the desired length. if, in your case, if it's always 3, you can replace {{{L}}} in the example with 3. in the general case, i thought it's better to leave it as a parameter. note that {{{P}}} appears several times - you should replace them all with the correct parameter name. alternatively, you can create a new template containing the code above, and pass to it these two params. i want to make one point again: this code does not check for the validity of the input: it assumes that you supply it with a string that contains zero or more non-digit characters, and then zero or more consecutive digits. it should handle your examples above the way you required, but if you pass something like "1C" and length 3, you will get "0" (no non-digits at the beginning and no digits at the end, so all is left is the padding, which only take into account the total length, i.e., 3-2). peace - קיפודנחש (aka kipod) (talk) 12:41, 19 March 2015 (UTC)