Documentação do módulo[ver] [editar] [histórico] [purgar]

Ce module contient différentes fonctions pratiques.

Résumé des fonctions editar

Fonctions exportables :

  • trim( texte ) – similaire à mw.text.trim mais retourne nil lorsque la chaine est vide ou lorsque le paramètre n'est pas une chaine (ne génère pas d'erreur).
  • extractArgs( frame ) – retourne une table avec les paramètres, à partir d'un objet frame ou d'une table.
  • validTextArg( args, name, ... ) – retourne le premier paramètre chaine non vide à partir de la table des paramètres et d'une liste de noms de paramètres.
  • notEmpty( var, ... ) – retourne le premier élément non vide.

Détail par fonction editar

extractArgs editar

Syntaxe editar

Outils.extractArgs( frame )

  • Si frame est une table simple et non un objet Frame, retourne frame
  • Si frame est un objet créé par #invoke:, retourne les paramètres passés à #invoke: (en priorité) et ceux passés au modèle.

Attention : cette fonction peut modifier la table frame.getParent().args. S'il est probable qu'un autre module passe un objet frame à votre fonction, il est préférable de l'indiquer dans la documentation.

Exemple editar
function p.maFonction( frame )
    local args = Outils.extractArgs( frame )
    return ( args[1] or 'nil' ) .. ' ' .. ( args[2] or 'nil' ) .. ' ' .. ( args['nom'] or 'nil' )
end
  • appel par table : p.maFonction{ 'oui', 'deux', nom = 'Zebulon84' } → « oui deux Zebulon84 »
  • appel par #invoke: : {{#invoke:p |maFonction |oui |2 |nom = Zebulon84}} → « oui deux Zebulon84 »
  • appel par modèle {{Ma fonction}} :
    • le modèle contient {{#invoke:p |maFonction}},
      • {{Ma fonction|oui | deux |nom= Zebulon84}} → « oui deux Zebulon84 »
    • le modèle contient {{#invoke:p |maFonction |nom = Zebulon84}}
      • {{Ma fonction |oui | deux }} → « oui deux Zebulon84 »
      • {{Ma fonction |oui | deux |nom = Hexasoft}} → « oui deux Zebulon84 »
    • le modèle contient {{#invoke:p |maFonction |nom = {{{nom|Zebulon84}}} }}
      • {{Ma fonction |oui | deux }} → « oui deux Zebulon84 »
      • {{Ma fonction |oui | deux |nom = Hexasoft}} → « oui deux Hexasoft »
      • {{Ma fonction |oui | deux |nom = }} → « oui deux nil »

validTextArg editar

Syntaxe editar

Outils.validTextArg( args, name, ... )

Retourne args.name si c'est un texte valide. Sinon teste les autres éléments transmis à la fonction. S'il n'y en a pas ou s'ils ne correspondent pas à un texte valide dans la table args, retourne nil

Cette fonction est pratique pour obtenir le contenu d'un paramètre pouvant avoir plusieurs noms.

Attention : les nombres (type 'number') ne sont pas considérés comme un texte valide.

exemple editar
local args = { '1', '2', 3, nom1 = nil, nom2 = '', nom3 = 'a' }
local v1  = Outils.validTextArg( args, 'nom1' }                -- v1 = nil
local v2 = Outils.validTextArg( args, 'nom1', 'nom2', 'nom3' ) -- v2 = 'a'
local v3 = Outils.validTextArg( args, 3, 2, 1 )                -- v3 = '2'

local function validArg( ... ) 
    return Outils.validTextArg( args, ... }
end

local v4 = validArg( 'nom' )  -- v4 = nil
local v5 = validArg( 'nom2', 'nom3' ) -- v5 = 'a'

notEmpty editar

Outils.notEmpty( var, ... )

Retourne le premier élément non vide, sinon retourne nil.

  • Sont considérés comme vide : nil, false, '', ' \t \n ', 0, { }
  • Sont considérés comme non vide : true, 'blabla', ' ', 1, { '' }, { {} }, function () end

local Utilidades = { }


--[[
    trim limpa um parâmetro sem nome (remove espaços iniciais e finais e retorna no início e no final)
retorna nil se o texto estiver vazio ou não for texto. Números não são considerados
como texto.
]]
function Utilidades.trim( texto )
    if type( texto ) == 'string' and texto ~= '' then
        texto = texto:gsub( '^%s*(%S?.-)%s*$', '%1' )
        if texto ~= '' then
            return texto
        end
    end
    return nil
end


--[[
    validTextArg retorna o primeiro parâmetro de string não vazio
    Parâmetro :
        1 - tabela contendo todos os parâmetros
        2, ... - os nomes dos parâmetros que devem ser testados.
]]
function Utilidades.validTextArg( args, name, ... )
    local texto = Utilidades.trim( args[name] )
    if texto then
        return texto
    end
    if select( '#', ... ) > 0 then
        return Utilidades.validTextArg( args, ... )
    end
    return nil
end


--[[
    notEmpty retorna o primeiro parâmetro não vazio ou nulo.
    Parâmetro :
        1, ... - os nomes dos parâmetros que devem ser testados.
]]
function Utilidades.notEmpty( var, ... )
    local texto = Utilidades.trim( var )
    if texto then
        return texto
    end
    local tvar = type( var )
   
    if tvar == 'table' then
        local nextFunc = pairs( var )   -- não use próximo car porque não está definido em par mw.loadData
        if nextFunc( var ) ~= nil then
            return var
        end
    elseif var == true or ( tvar == 'number' and var ~= 0 ) or tvar == 'function' then
        return var
    end
    if select( '#', ... ) > 0 then
        return Utilidades.notEmpty( ... )
    end
end


--[[
    extractArgs recupera os argumentos do modelo, ou a tabela
    passada para a função por outra função de um módulo,
    Parâmetro :
        1 - um objeto de quadro ou uma tabela contendo os parâmetros
        2, ...  - uma lista de nomes de parâmetros para determinar se os parâmetros são passados
        por #invoke. O primeiro parâmetro do frame será sistematicamente testado.
]]
function Utilidades.extractArgs ( frame )
    if type( frame.getParent ) == 'function' then
        local args = frame:getParent().args
        for k,v in pairs( frame.args ) do
            args[k] = v;
        end
        return args
    else
        return frame
    end
end


return Utilidades