Modulo:String/sandbox: differenze tra le versioni
Contenuto cancellato Contenuto aggiunto
test per infobox list |
rimuovo funzione incompleta e rimpiazzata da Modulo:IP validator |
||
(52 versioni intermedie di 2 utenti non mostrate) | |||
Riga 122:
{{#invoke:String|match|source_string|pattern_string|start_index|match_number|plain_flag|nomatch_output}}
O
{{#invoke:String|
|match=match_number|plain=plain_flag|nomatch=nomatch_output}}
Riga 148:
]]
function str.match(
return str._match(frame.args)
end
--[[
Entry point per chiamata diretta da un modulo
]]
function str._match( args )
local new_args = str._getParameters( args, {'s', 'pattern', 'start', 'match', 'plain', 'nomatch'} );
local s = new_args['s'] or '';
local start = tonumber( new_args['start'] ) or 1;
Line 158 ⟶ 165:
if s == '' then
return nomatch or str._error( 'La stringa in cui cercare è vuota' );
end
if pattern == '' then
return nomatch or str._error( 'La stringa o pattern da cercare è vuota' );
end
if math.abs(start) < 1 or math.abs(start) > mw.ustring.len( s ) then
return nomatch or str._error( 'La posizione iniziale richiesta è fuori dagli estremi della stringa' );
end
if match_index == 0 then
return nomatch or str._error( 'Match index è nullo' );
end
if plain_flag then
Line 388 ⟶ 395:
--[[
Funzione per utilizzare string.rep in un
]]
Line 404 ⟶ 411:
--[[
Funzione per
Richiama la funzione mw.uri.decode di scribunto, vedi
https://www.mediawiki.org/wiki/Extension:Scribunto/Lua_reference_manual#mw.uri.decode
]]
function str.decode( frame )
local valid_enctype = { QUERY = true, WIKI = true, PATH = true}
local new_args = str._getParameters(frame.args, {'source', 'enctype'})
local source = new_args['source'] or ''
local enc_type = new_args['enctype'] or 'QUERY'
if not valid_enctype[enc_type] then
enc_type = 'QUERY'
end
return mw.uri.decode(source, enc_type)
end
--[[
Funzione per semplificare stringhe con diacritici
]]
function str.collate( frame )
local collation = {
{ '[áàăắằẵẳâấầẫẩǎåǻäǟãȧǡąāảȁȃạặậḁⱥᶏᴂɐᶐɒ]' , 'a'},
{'[ÁÀĂẮẰẴẲÂẤẦẪẨǍÅÅǺÄǞÃȦǠĄĀẢȀȂẠẶẬḀȺᴁ]', 'A'},
{'[ḃḅḇbƀɓ]', 'b'},
{'[ḂḄḆɃ]', 'B'},
{'[ćĉčċçḉȼƈ]', 'c'},
{'[ĆĈČĊÇḈȻƇ]', 'C'},
{'[đḍḓḏðď]', 'd'},
{'[ĐḌḒḎÐĎ]', 'D'},
{'[éèèêếềễểěëẽėȩḝęēḗḕẻȅȇẹệḙḛǝ]', 'e'},
{'[ÉÈÈÊẾỀỄỂĚËẼĖȨḜĘĒḖḔẺȄȆẸỆḘḚƎ]', 'E'},
{'[ḟⅎ]', 'f'},
{'[ḞℲ]', 'F'},
{'[ǵğĝǧġģḡᵹɠ]', 'g'},
{'[ǴĞĜǦĠĢḠƓ]', 'G'},
{'[ĥȟḧḣḩħḥḫẖ]', 'h'},
{'[ĤȞḦḢḨĦḤḪ]', 'H'},
{'[íìĭîǐïḯĩįīỉȉȋịḭı]', 'i'},
{'[ÍÌĬÎǏÏḮĨĮĪỈȈȊỊḬİ]', 'I'},
{'[ĵǰ]', 'j'},
{'[Ĵ]', 'J'},
{'[ḱǩķ]', 'k'},
{'[ḰǨĶ]', 'K'},
{'[ĺľļłḷḹḽḻl·l·ŀƚⱡ]', 'l'},
{'[ĹĽĻŁḶḸḼḺL·L·ĿȽⱠ]', 'L'},
{'[ḿṁṃ]', 'm'},
{'[ḾṀṂ]', 'M'},
{'[ńǹňñṅņṇṋṉ]', 'n'},
{'[ŃǸŇÑṄŅṆṊṈ]', 'N'},
{'[óòŏôốồỗổǒöȫőõṍṏȭȯȱøǿǫǭōṓṑỏȍȏơớờỡởợọộ]', 'o'},
{'[ÓÒŎÔỐỒỖỔǑÖȪŐÕṌṎȬȮȰØǾǪǬŌṒṐỎȌȎƠỚỜỠỞỢỌỘ]', 'O'},
{'[ṕṗ]', 'p'},
{'[ṔṖ]', 'P'},
{'[ŕřṙŗȑȓṛṝṟ]', 'r'},
{'[ŔŘṘŖȐȒṚṜṞ]', 'R'},
{'[śṥŝšṧṡşṣṩș]', 's'},
{'[ŚṤŜŠṦṠŞṢṨȘ]', 'S'},
{'[ťṫẗţṭțṱṯ]', 't'},
{'[ŤṪŢṬȚṰṮ]', 'T'},
{'[úùŭûǔůüǘǜǚǖűũṹųūṻủȕȗưứừữửựụṳṷṵʉ]', 'u'},
{'[ÚÙŬÛǓŮÜǗǛǙǕŰŨṸŲŪṺỦȔȖƯỨỪỮỬỰỤṲṶṴɄ]', 'U'},
{'[ṽṿʋ]', 'v'},
{'[ṼṾƲ]', 'V'},
{'[ẃẁŵẘẅẇẉⱳ]', 'w'},
{'[ẂẀŴ̊ẄẆẈⱲ]', 'W'},
{'[ýỳŷẙÿỹẏȳỷỵɏƴ]', 'y'},
{'[ÝỲŶ̊ŸỸẎȲỶỴɎƳ]', 'Y'},
{'[źẑžżẓẕƶȥʐⱬ]', 'z'},
{'[ŹẐŽŻẒẔƵȤʐⱫ]', 'Z'},
}
local new_args = str._getParameters(frame.args, {'source'})
local source = new_args['source'] or ''
--local source = mw.ustring.toNFC(source)
for _, el in ipairs(collation) do
source = mw.ustring.gsub( source, el[1], el[2])
end
return source
end
--[[
Funzione per estrarre da un titolo la stringa adatta all'ordinamento alfabetico.
]]
function str.titolo_alfa(frame)
-- Evito "I", "A", "Die"... che darebbero molte false corrispondenze in lingue diverse
local articoli = {"Il ", "Lo ", "La ", "L'", "Gli ", "Le ", "Un ", "Uno ", "Una ", "Un'", "The ", "An ", "Les ", "El ", "Los ", "Las ", "Der ", "Das "}
local source = frame.args[1]
if not source or source == '' then
source = mw.title.getCurrentTitle().text
end
if not source or source == '' then
return ''
end
source = mw.ustring.gsub(source, ' %(.*%)$', '')
source = str.collate( { args = { source } } )
source = mw.ustring.gsub(source, "^['%(%.¡¿ ]*", '')
for _,article in ipairs(articoli) do
source = mw.ustring.gsub(source, "^(" .. article .. ")(.*)$", "%2, %1")
end
source = mw.ustring.gsub(source, '^%l', mw.ustring.upper)
source = mw.text.trim(source)
return source
end
-- =================================================================
-- Classe per gestire i parametri
-- =================================================================
local Param = {}
Param.__index = Param
function Param.new(par_name, alt_name)
if par_name ~= "$index" and not mw.ustring.find(par_name, '#') then par_name = par_name .. '#' end;
return setmetatable({
name = par_name,
base_name = mw.ustring.gsub(par_name, ' ?#', '', 1),
alt = alt_name or ''
}, Param)
end
function Param:get_other_value(args, index)
if self.name == '$index' then
return tostring(index), true
else
return args[mw.ustring.gsub(self.name, '#', tostring(index), 1)] or '', false
end
end
function Param:get_first_value(args, index, base_index)
function value_or_nil (s)
if s and s~= '' then return s end
return nil
end
if self.name == '$index' then
return tostring(index), true
end
if index == base_index then
return value_or_nil(args[mw.ustring.gsub(self.name, '#', tostring(index), 1)]) or
value_or_nil(args[self.base_name]) or value_or_nil(args[self.alt]) or '', false
else
return value_or_nil(args[mw.ustring.gsub(self.name, '#', tostring(index), 1)]) or
value_or_nil(args[self.alt]) or '', false
end
end
setmetatable(Param, { __call = function(_, ...) return Param.new(...) end })
-- =================================================================
-- fine dichiarazione classe per parametro
-- =================================================================
-- =================================================================
-- Classe per gestire il messaggio
-- =================================================================
local Message = {}
Message.__index = Message
function Message.new(msg)
-- converto parentesi graffe che sono state precedute da "\"
msg = mw.ustring.gsub(msg, '\\{', '{')
msg = mw.ustring.gsub(msg, '\\}', '}')
local frame = mw.getCurrentFrame():getParent() or mw.getCurrentFrame()
return setmetatable({
msg = msg,
values = {},
frame = frame,
}, Message)
end
function Message:reset_values()
self.values = {}
end
function Message:add_value(value)
self.values[#self.values+1] = value
end
function Message:text()
return self.frame:preprocess(mw.message.newRawMessage(self.msg, self.values):plain())
end
setmetatable(Message, { __call = function(_, ...) return Message.new(...) end })
-- =================================================================
-- fine dichiarazione classe per messaggio
-- =================================================================
--[[
Funzione per unire una o più liste di valori in una stringa.
Uso:
{{#invoke:String|arraytostring|
Parametri:
posizione in cui inserire l'indice. Se viene valorizzato a '$index' avrà automaticamente il valore del
contatore.
msg: il messaggio (cioè la riga unitaria) in cui eventuali caratteri '{', '}' dovranno essere
preceduti da '\', mentre una "|" dovrà essere inserita con il template {{!}}.
I valori da sostituire sono da inserire come $n ($1 sarà sostituito dal
valore di par1, $2 dal valore di par2, ecc...)
separatore: La stringa da inserire tra ogni valore
congiunzione: La stringa da inserire invece di separatore tra l'ultimo e il penultimo valore. Se
non precisato viene usato il valore di separatore
pre: eventuale stringa che precede l'unione delle stringhe
post: eventuale stringa che segue l'unione delle stringhe
indentazione: una stringa da ripetere cumulativamente per ogni messaggio (tipicamente ' ')
lista: se valorizzata a:
'puntata' imposta i parametri per una lista puntata
'ordinata' imposta i parametri per una lista ordinata
'infobox' imposta l'unione come una lista, eccetto che nel caso ci sia
solo un elemento
Se lista è valorizzata separatore/congiunzione/pre/post sono ignorati, salvo il caso di 'infobox' e la
lista contenga solo un elemento.
nmin = indice iniziale da cui partire a scandire i parametri (di default pari a 1)
nmax = indice massimo a cui arrivare con i parametri (se non precisato illimitato)
nobbligatori = l'indice minimo che deve essere valutato anche in presenza di buchi nella sequenza (comunque l'indice massimo
che viene valutato è nmax)
baseIndex = valore dell'indice che può essere sostituito da stringa nulla (default = 1)
Esempi di chiamata:
{{#invoke:string:arraytostring|par1=var#|separatore=,|congiunzione=#32;e#32;}}
{{#invoke:string:arraytostring|par1=disegnatore #|par2=disegnatore # nota|msg = $1 <small>$2</small>|lista=infobox }}
{{#invoke:string:arraytostring|par1=editore #|par2=etichetta #|par3=editore # nota| msg=$1 \{\{#if:$2{{!}}$2 <small>$3</small>\}\}|lista=infobox }}
]]
function str.arraytostring(frame)
local base_args = frame.args
local
if not
-- carico la lista dei parametri
local index = 1
while true do
local par_name = base_args['par' .. index] or (index == 1 and base_args['par']) or ''
if par_name == '' then break end;
--carico eventuale nome alternativo per il primo parametro
local alt_name = base_args['altpar' .. index] or (index == 1 and base_args['altpar']) or ''
params[index] = Param(par_name, alt_name)
index = index + 1
end
--carico il messaggio
local msg = base_args.msg or '$1'
--if msg == '' then return str._error('Manca il messaggio da riprodurre.') end
local
-- carico gli altri parametri di formattazione
local Nmax = tonumber(
local base_index = tonumber(base_args.baseindex) or tonumber(base_args.baseIndex) or 1
local index = tonumber(base_args.Nmin) or tonumber(base_args.nmin) or base_index
local Nobbligatori = tonumber(base_args.Nobbligatori) or tonumber(base_args.nobbligatori) or base_index-1
local indentazione = base_args.indentazione or nil
local args = frame:getParent().args
-- estraggo il primo valore
local found = false
for i, param in ipairs(params) do
local v, is_index = param:get_first_value(args, index, base_index)
if (not(is_index) or base_index<=Nobbligatori) and v ~= '' then found = true end
message:add_value(v)
end
if found then
elements[#elements+1] = message:text()
index = index + 1
end
-- elaboro i valori successivi
while true do
if Nmax > 0 and index > Nmax then break end
message:reset_values()
found = false
for i, param in ipairs(params) do
local v, is_index = param:get_other_value(args, index)
if (not(is_index) or index<=Nobbligatori) and v ~= '' then found = true end
message:add_value(v)
end
if found then
elements[#elements+1] = message:text()
elseif index >= Nobbligatori then
break
end
index = index + 1
end
if #elements == 0 then return '' end
-- carico separatori, congiunzione, pre e postazione
local pre, post, separatore, congiunzione, indent = '', '', '', '', ''
local lista = base_args.lista or ''
if lista == 'puntata' or (lista =='infobox' and #elements >1) then
pre = '<UL><LI>'
post = '</LI>\n</UL>'
separatore = '</LI>\n<LI>'
congiunzione = separatore
elseif lista == 'ordinata' then
pre = '<OL><LI>'
post = '</LI>\n</OL>'
separatore = '</LI>\n<LI>'
congiunzione = separatore
else
pre = base_args.pre or ''
post = base_args.post or ''
separatore = base_args.separatore or ''
congiunzione = base_args.congiunzione or separatore
end
if indentazione then
local current_indentazione = indentazione
for i, msg in ipairs(elements) do
elements[i] = current_indentazione .. elements[i]
current_indentazione = current_indentazione .. indentazione
end
end
return pre .. mw.text.listToText(elements, separatore, congiunzione) .. post
end
--[[
Funzione per unire una lista di valori in una stringa.
Uso:
{{#invoke:String|listtostring|par_number=xxx|msg=msg|separator=|congiunzione=|pre=|post=|lista=}}
Parametri:
par_number: il numero di parametri che compongono il messaggio
msg: il messaggio (cioè la riga unitaria) in cui eventuali caratteri '{', '}' dovranno essere
preceduti da '\', mentre una "|" dovrà essere inserita con il template {{!}}.
I valori da sostituire sono da inserire come $n (nel primo messaggio $1 sarà sostituito dal parametro posizionale di
posizione Nmin, $2 da Nmin+2, ecc...., nel secondo messaggio $1 sarà sostituito dal parametro posizionale Nmin+par_number,
$2 da Nmin+par_number+2, ec....)
valore di par1, $2 dal valore di par2, ecc...)
separatore: La stringa da inserire tra ogni valore
congiunzione: La stringa da inserire invece di separatore tra l'ultimo e il penultimo valore. Se
non precisato viene usato il valore di separatore
pre: eventuale stringa che precede l'unione delle stringhe
post: eventuale stringa che segue l'unione delle stringhe
lista: se valorizzata a:
'puntata' imposta i parametri per una lista puntata
'ordinata' imposta i aprametri per una lista ordinata
'infobox' imposta l'unione come una lista, eccetto che nel caso ci sia
solo un elemento
Se lista è valorizzata separatore/congiunzione/pre/post sono ignorati, salvo il caso di 'infobox' e la
lista contenga solo un elemento.
nmax = indice massimo a cui arrivare con i parametri (se non precisato illimitato)
nobbligatori = l'indice minimo che deve essere valutato anche in presenza di buchi nella sequenza (comunque l'indice massimo
che viene valutato è nmax)
baseIndex = valore del primo parametro posizionale da cui cominciare a leggere (default = 1)
]]
function str.listtostring(frame)
local base_args = frame.args
local params = {}
if not
-- carico la lista dei parametri
local
local par_number = tonumber(base_args.par_number) or 1
local Nmax = tonumber(base_args.nmax) or 0
local Nobbligatori = tonumber(base_args.nobbligatori) or base_index-1
--carico il messaggio
local message = Message(base_args.msg or '$1')
elements = {}
-- carico gli altri parametri di formattazione
local index = base_index
local args = frame:getParent().args
-- elaboro i valori successivi
local found = true
while true do
message:reset_values()
found = false
for i = index, index+par_number-1 do
message:add_value(args[i] or '')
if args[i] then
found = true
end
end
elements[#elements+1] = message:text()
elseif index > Nobbligatori then
end
end
if #elements == 0 then return '' end
-- carico separatori, congiunzione, pre e postazione
local pre, post, separatore, congiunzione = '', '', '', ''
local lista = base_args.lista or ''
if lista == 'puntata' or (lista =='infobox' and #elements >1) then
pre = '<UL><LI>'
post = '</LI>\n</UL>'
separatore = '</LI>\n<LI>'
congiunzione = separatore
elseif lista == 'ordinata' then
pre = '<OL><LI>'
post = '</LI>\n</OL>'
separatore = '</LI>\n<LI>'
congiunzione = separatore
else
pre = base_args.pre or ''
post = base_args.post or ''
separatore = base_args.separatore or ''
congiunzione = base_args.congiunzione or separatore
end
return pre .. mw.text.listToText(elements, separatore, congiunzione) .. post
end
|