Module:Sandbox/Wladek92/luatest1
Appearance
Module documentation
[create]
-- https://en.wikipedia.org/wiki/Module:Example
-- Christian Wiat : Introduction to Lua in Wikipedia - this is my sandbox.
-- ogechi Outreachy Introduction to Lua in Wikipedia
--- Example module.
-- @module example
-- @alias p
local p = {} --All Lua modules on Wikipedia must begin by defining a variable
--that will hold their >>>> externally accessible functions <<<<
--contain various data as well as functions.
-- les fonctions sont placées d'office dans la p pour les besoins de #invoke
-- elles peuvent exister en dehors
-- https://fr.wikiversity.org/wiki/Initiation_au_Lua_avec_Scribunto/Premi%C3%A8res_notions
-- 1. utiliser elseif
-- 2. Mise au point d'un module
-- 3.Initiation_au_Lua_avec_Scribunto/Tables_et_fonctions
function p.alea(frame)
local seed = frame.args[1] --seed= tjours arg1
local reponse = ''
if seed and seed ~='' then math.randomseed(tonumber(seed)) end -- ||=absent; réarmer si présent
local m,n = frame.args[2],frame.args[3] -- bornes min max
for x = 1, 20 do --générer 20 nombres
if m ~= nil and n ~= nil then
reponse = reponse..math.random(m,n).." " --dans [m,n[
elseif m ~= nil then
reponse = reponse..math.random(m).." " --dans [1,m[
else
reponse = reponse..math.random().." " --dans [0:1[
end
end
return reponse
end
function stdio()
return [[ io is not available:
1. clé '''close''' type : function
2. clé '''input''' type : function
3. clé '''tmpfile''' type : function
4. clé '''popen''' type : function
-- clé '''stdin''' type : userdata
5. clé '''type''' type : function
-- clé '''stdout''' type : userdata
6. clé '''write''' type : function
7. clé '''lines''' type : function
-- clé '''stderr''' type : userdata
8. clé '''flush''' type : function
9. clé '''open''' type : function
10. clé '''output''' type : function
11. clé '''read''' type : function]]
end
-- liste les fonctions disponibles dans une bibliothèque
function stdFunc(lib)
local reponse=''
local i = 0
for index, objet in pairs(lib) do
local t = type(objet)
if t == 'function' then -- incrementer le nbre de fonctions
i = i + 1
sep=tostring(i)
else -- ce n'est pas une fonction
sep='--'
end
reponse = reponse.."<br />"..sep.." clé '''"..index.."''' type : "..type(objet)
end
return reponse
end
function p.stdLib(frame)
local reponse=''
local lib = frame.args[1]
if lib=='string' then reponse=stdFunc(string)
elseif lib=='table' then reponse=stdFunc(table)
elseif lib=='io' then reponse=stdio() -- non Scribunto
elseif lib=='math' then reponse=stdFunc(math)
elseif lib=='os' then reponse=stdFunc(os)
elseif lib=='debug' then reponse=stdFunc(debug)
elseif lib=='mw' then reponse=stdFunc(mw)
elseif lib=='ustring' then reponse=stdFunc(mw.ustring)
elseif lib=='text' then reponse=stdFunc(mw.text)
-- elseif lib=='bitwise' then reponse=stdFunc(bit32)
else reponse='lib non reconnue: '..lib
end
return reponse
end
--[[clé '''dump''' type : function
clé '''find''' type : function
clé '''match''' type : function
clé '''sub''' type : function
clé '''char''' type : function
clé '''reverse''' type : function
clé '''pack''' type : function
clé '''rep''' type : function
clé '''format''' type : function
clé '''lower''' type : function
clé '''byte''' type : function
clé '''len''' type : function
clé '''unpack''' type : function
clé '''packsize''' type : function
clé '''upper''' type : function
clé '''gsub''' type : function
clé '''gmatch''' type : function table]]
e1 = function(num, wish)
if num ==1 then error("Error with stack level -> "..tostring(num).." wished depth:"..tostring(wish), wish)
else e2(num, wish)
end
end
e2 = function(num, wish)
if num ==2 then error("Error with stack level -> "..tostring(num).." wished depth:"..tostring(wish), wish)
else e3(num, wish)
end
end
e3 = function(num, wish)
if num ==3 then error("Error with stack level -> "..tostring(num).." wished depth:"..tostring(wish), wish)
else e4(num, wish)
end
end
e4 = function(num,wish)
if num ==4 then error("Error with stack level -> "..tostring(num).." wished depth:"..tostring(wish), wish)
else e5(num, wish)
end
end
e5 = function(num,wish)
if num ==5 then error("Error with stack level -> "..tostring(num).." wished depth:"..tostring(wish), wish)
else e6(num, wish)
end
end
e6 = function(num,wish)
if num ==6 then error("Error with stack level -> "..tostring(num).." wished depth:"..tostring(wish), num)
else error("Error with upper stack level > 6 -> "..tostring(num).." wished depth:"..tostring(wish), wish)
end
end
p.err = function(frame)
--[[frame=mw.getCurrentFrame()
newframe=frame:newChild{args={'0','0'}}
=p.err(newframe)
]]
local t = frame.args[1]
local trigger = tonumber(t) -- niveau trigger qui produit l'erreur
local d = frame.args[2]
local depth = nil
if d==nil then depth =0
else depth = tonumber(d) --niveau de détails dans la pile
end
--mw.log("msg console debug -> " ..t..' / '..d)
--error("Error at basic stack level -> "..t.." wished depth: "..d)
if trigger==0 then error("basic stack level -> "..trigger.." wished depth: "..depth, depth)
else e1(trigger, depth)
end
end
-- ----------------------------------------------------------------------------------------
-- format séquence : liste d'indices numerotée 1,2,3....
local semaine = {"lundi", "mardi", "mercredi", "jeudi", "vendredi", "samedi", "dimanche"}
-- format record : clé = valeur la clé est une string; accès direct avec la clé style record: sem.Lundi
local sem = { ["lundi"] = "monday", ["mardi"] = "tuesday", ["mercredi"] = "wednesday",
["jeudi"] = "thursday", ["vendredi"] = "friday", ["samedi"] = "saturday", ["dimanche"] = "sunday"}
-- table de table = matrices = [ligne] [colonne] c'est une séquence de séquences A[2][3].
local A = {{2,1,-4,6},{5,-3,-2,4},{1,3,-4,7},{-5,3,2,5}}
local tab=' ' -- default to html space separator or '\t' for console
local cr='<br />' -- default to html tag newline or '\n' for console
local env='browser' -- environnement: browser / debug
--[[
table.insert(t, ligne) : incrémente la table avec "ligne".
table.remove(t,ligne) : retire un élément de la table.
table.concat(t, séparateur) : convertit la table en une chaîne de caractères, en séparant chaque ligne par une éventuelle autre chaîne.
table.maxn(t) : renvoie le plus grand index numérique positif utilisé dans la table.
table.sort(t) : permet de trier la table.
table.getn(t) : renvoie la taille de la table.
]]
--fonctions locales qui ne sont pas dans p
function spechar (argum) -- normaliser les séparateurs
-- argum : liste des paramètres d'appel
if argum.env ~= nil then env=argum.env end
if argum.tab ~= nil then tab=argum.tab
elseif env=="debug" then tab="\\t"
end
if argum.cr ~= nil then cr=argum.cr
elseif env=="debug" then cr="\\n"
end
mw.log("msg console debug -> environment >>"..env.."<<")
mw.log("msg console debug -> tabulation >>"..tab.."<<")
mw.log("msg console debug -> newline >>"..cr.."<<")
end
function sizeV(mat)
return #mat
end
function sizeL(mat)
return #mat[1]
end
--[[ frame=mw.getCurrentFrame()
newframe=frame:newChild{args={''}}
=p.matrixdump(newframe)
frame=mw.getCurrentFrame()
newframe=frame:newChild{args={["env"]="browser"}}
=p.matrixdump(newframe)
* Format demandé Console debug :{{#invoke:Sandbox/Wladek92/luatest1|matrixdump|env=debug}}
* Format demandé Console debug avec séparateurs:{{#invoke:Sandbox/Wladek92/luatest1|matrixdump|env=debug|tab= |cr=\010}}
]]
function p.matrixdump(frame)
local s='Matrice A :\n'
local nbline=sizeV(A)
local nbcols=sizeL(A)
spechar(frame.args) -- evaluate parameters
if env=="browser" then s=s.."<pre>" end
for i=1, nbline do -- sur toutes les lignes
for j=1,nbcols do
if env == 'browser' then
s=s..tab..A[i][j]
else
s=s.."\t"..A[i][j]
end
end
if env == 'browser' then
s=s..cr
else
s=s.."\n" -- s=s.."\010" --new line
end
end
if env=="browser" then s=s.."</pre>" end
return s
end
function p.traduit(frame)
--[[ console debug: simuler une frame avec des paramètres
frame=mw.getCurrentFrame()
newframe=frame:newChild{args={'Jeudi'}}
=p.traduit(newframe)
Thursday
newframe=frame:newChild{args={'Jeudi','ES'}}
=p.traduit(newframe) Jueves
frame=mw.getCurrentFrame()
newframe=frame:newChild{args={'1','EN','num'}}
=p.traduit(newframe)
newframe=frame:newChild{args={'1','ES','num'}}
=p.traduit(newframe)
frame=mw.getCurrentFrame()
newframe=frame:newChild{args={'jeudi','EN'}}
=p.traduit(newframe)
]]
local jour=''
if frame.args[3] == "num" then
jour = semaine[ tonumber(frame.args[1]) ]
else
jour = frame.args[1]
end
jour=string.lower(jour) --normaliser en minuscules
mw.log("msg console debug -> " .. jour)
local param2 = frame.args[2]
if param2 == nil then param2="EN" end
mw.log("msg console debug -> " .. param2 )
if param2 == "ES" then
if jour == semaine[1] then
return "Lunes"
elseif jour == "mardi" then
return "Martes"
elseif jour == "mercredi" then
return "Miércoles"
elseif jour == "jeudi" then
return "Jueves"
elseif jour == "vendredi" then
return "Viernes"
elseif jour == "samedi" then
return "Sábado"
elseif jour == "dimanche" then
return "Domingo"
else error("dico ES: jour invalide")
end
else
return sem[jour].."\nRappel: premier jour de la semaine anglaise -> "..sem["lundi"].." , dernier jour -> "..sem.dimanche
-- jour=clé du record -> directement le jour en anglais
end
end
-- pairs: récupération des index des séquences et des clés des records
function p.getArgsWithPairs(frame)
local tab=frame.args
local reponse = " "
local i = 0
for index, objet in pairs(tab) do
reponse = reponse.."<br />à la clé "..index.." se trouve l’objet "..objet.."."
i = i + 1
end
return reponse..'['..tostring(i)..']'
end
function p.getArgs(frame)
local tab=frame.args
return p.getTableKeys(tab)
end
function p.getLoaded() --liste des bibliothèques chargées
return p.getTableKeys(package.loaded)
end
function p.getTableKeys(tab)
--[[ console debug :
=p.getTableKeys({jour="lundi", semaine="23"})
Clé trouvée : jour
Clé trouvée : semaine
[2] :<br/><br/> jour<br/> semaine
]]
local keyset = {}
local keystring =''
for k,_ in pairs(tab) do -- la valeur est ignorée
mw.log("Clé trouvée : ", k)
--keyset[#keyset + 1] = k other method
table.insert(keyset, k)
keystring=keystring..'<br/> '..k
end
return '['..#keyset..'] :<br/>'..keystring
-- return keyset
end
function p.lgthframe(frame)
return #frame
end
function p.typeframe(frame)
return type(frame)
end
function p.argframe(frame)
-- return frame.args -- rend une table
return frame.args[0]
-- return frame.args.p1..frame.args.p2
end
--- Hello world function
-- @param {table} frame current frame
-- @return Hello world
p.hello = function( frame ) --Add a function to "p".
--Such functions are callable in Wikipedia
--via the #invoke command.
--"frame" will contain the data that Wikipedia
--sends this function when it runs.
-- 'Hello' is a name of your choice. The same name needs to be referred to when the module is used.
local str = "Hello World!" --Declare a local variable and set it equal to
--"Hello World!".
return str --This tells us to quit this function and send the information in
--"str" back to Wikipedia.
end -- end of the function "hello"
function p.helloMonde()
mw.log("placer ici le msg console debug -> none")
return "Bonjour le monde !"
end
p.Hi = function(frame)
local strName
strName = frame.args.name or "oge"
return "Hello from Lua to my friend " .. strName .. ".<br>"
end
--- Hello world function
-- @param {table} frame current frame
-- @param {string} frame.args[1] name
-- @return Hello world
function p.hello_to(frame) -- Add another function
local name = frame.args[1] -- To access arguments passed to a module, use `frame.args`
-- `frame.args[1]` refers to the first unnamed parameter
-- given to the module
return "Hello, " .. name .. "!" -- `..` concatenates strings. This will return a customized
-- greeting depending on the name given, such as "Hello, Fred!"
end
--- Counts fruit
-- @param {table} frame current frame
-- @param {string} frame.args.bananas number of bananas
-- @param {string} frame.args.apples number of apples
-- @return Number of apples and bananas
function p.count_fruit(frame)
local num_bananas = tonumber(frame.args.bananas) or 0 -- Named arguments ({{#invoke:Example|count_fruit|foo=bar}})
local num_apples = tonumber(frame.args.apples) or 0 -- are likewise accessed by indexing `frame.args` by name (`frame.args["bananas"]`,
-- or equivalently `frame.args.bananas`.
local conj_bananas = num_bananas == 1 and 'banana' or 'bananas'
local conj_apples = num_apples == 1 and 'apple' or 'apples'
-- Ternary operators assign values based on a condition in a compact way.
-- Here, `conj_bananas` gets `'banana'` if `num_bananas` is 1, else `'bananas'`.
-- Similarly, `conj_apples` gets `'apple'` if `num_apples` is 1, else `'apples'`.
return 'I have ' .. num_bananas .. ' ' .. conj_bananas .. ' and ' .. num_apples .. ' ' .. conj_apples
-- Like above, concatenate a bunch of strings together to produce
-- a sentence based on the arguments given.
end
--- Lucky function
-- @param {string} a
-- @param {string} b
-- @return Whether a is lucky.
local function lucky(a, b) -- One can define custom functions for use. Here we define a function 'lucky' that has two inputs a and b. The names are of your choice.
if b == 'yeah' then -- Condition: if b is the string 'yeah'. Strings require quotes. Remember to include 'then'.
return a .. ' is my lucky number.' -- Outputs 'a is my lucky number.' if the above condition is met. The string concatenation operator is denoted by 2 dots.
else -- If no conditions are met, i.e. if b is anything else, output specified on the next line. 'else' should not have 'then'.
return a -- Simply output a.
end -- The 'if' section should end with 'end'.
end -- As should 'function'.
--- Name2
-- @param {table} frame current frame
-- @return Some output
function p.Name2(frame)
-- The next five lines are mostly for convenience only and can be used as is for your module. The output conditions start on line 50.
local pf = frame:getParent().args -- This line allows template parameters to be used in this code easily. The equal sign is used to define variables. 'pf' can be replaced with a word of your choice.
local f = frame.args -- This line allows parameters from {{#invoke:}} to be used easily. 'f' can be replaced with a word of your choice.
local M = f[1] or pf[1] -- f[1] and pf[1], which we just defined, refer to the first parameter. This line shortens them as 'M' for convenience. You could use the original variable names.
local m = f[2] or pf[2] -- Second shortened as 'm'.
local l = f.lucky or pf.lucky -- A named parameter 'lucky' is shortend as l. Note that the syntax is different from unnamed parameters.
if m == nil then -- If the second parameter is not used.
return 'Lonely' -- Outputs the string 'Lonely' if the first condition is met.
elseif M > m then -- If the first condition is not met, this line tests a second condition: if M is greater than m.
return lucky(M - m, l) -- If the condition is met, the difference is calculated and passed to the self defined function along with l. The output depends on whether l is set to 'yeah'.
else
return 'Be positive!'
end
end
return p --All modules end by returning the variable containing their functions to Wikipedia.
-- Now we can use this module by calling {{#invoke: Example | hello }},
-- {{#invoke: Example | hello_to | foo }}, or {{#invoke:Example|count_fruit|bananas=5|apples=6}}
-- Note that the first part of the invoke is the name of the Module's wikipage,
-- and the second part is the name of one of the functions attached to the
-- variable that you returned.
-- The "print" function is not allowed in Wikipedia. All output is accomplished
-- via strings "returned" to Wikipedia.