Модуль:Приклад
Зовнішній вигляд

![]() | Ця сторінка не є пісочницею. Вона не повинна використовуватись для пробних редагувань. З метою поекспериментувати, будь ласка, перейдіть до пісочниці, вашої чернетки або інших пісочниць. |
Це приклад документації для модуля, який використовується для демонстрацій і подібного.
Див. також
[ред. код]- Модуль:Пісочниця: Для практики або експериментальних/тестувальних модулів.
Документація вище включена з Модуль:Приклад/документація. (ред. | історія) Дописувачі можуть експериментувати на підсторінках пісочниця (створити | дзеркало) та протестувати зміни (ред.) цього модуля. Будь ласка, додавайте категорії до підсторінки /документація. Підсторінки цієї сторінки. |
local p = {} --Усі модулі Lua у Вікіпедії повинні починатися з визначення змінної,
--яка міститиме їхні функції, що доступні зовні.
--Такі змінні можуть мати будь-яке ім'я, яке ви хочете та можуть
--також містити різні дані, а також функції.
p.hello = function( frame ) --Додає функцію до «p».
--Такі функції викликаються у Вікіпедії
--через команду #invoke.
--«frame» буде містити дані, які Вікіпедія
--відправляє до цієї функції, коли вона виконується.
-- «Hello» є назвою на ваш вибір. Така ж назва повинна бути використана, коли викликається модуль.
local str = "Привіт, світе!" --Визначається локальна змінна та її значенням є
--«Привіт, світе!».
return str --Це каже про те, щоб покинути цю функцію та відправити інформацію в
--«str» назад до Вікіпедії.
end -- кінець функції «hello»
function p.hello_to(frame) -- Додаємо іншу функцію
local name = frame.args[1] -- Щоб отримати доступ до переданих аргументів до модуля, використовуємо «frame.args»
-- «frame.args[1]» покликається на перший неіменований параметр
-- передаємо його значення до модуля
return "Привіт, " .. name .. "!" -- «..» виконує конкатенацію рядків. Це поверне підлаштоване
-- привітання залежно від переданого імені, наприклад «Привіт, Іване!»
end
function p.count_fruit(frame)
local num_bananas = tonumber(frame.args.bananas) or 0 -- До іменованого параметра ({{#invoke:Example|count_fruit|foo=bar}})
local num_apples = tonumber(frame.args.apples) or 0 -- можна отримати доступ через ідекс «frame.args» за ім'ям («frame.args["bananas"]»,
-- або його еквівалент «frame.args.bananas». Примітка: для кириличних назв параметрів використовується лише «frame.args["банани"]»
local conj_bananas = num_bananas == 1 and 'banana' or 'bananas'
local conj_apples = num_apples == 1 and 'apple' or 'apples'
-- Тернарні оператори призначають значення на основі умови в компактному вигляді.
-- Тут, «conj_bananas» отримує «'banana'», якщо «num_bananas» є 1, в іншому випадку — «'bananas'».
-- Подібно, «conj_apples» отримує «'apple'», якщо «num_apples» є 1, в іншому випадку — «'apples'».
return 'I have ' .. num_bananas .. ' ' .. conj_bananas .. ' and ' .. num_apples .. ' ' .. conj_apples
-- Як вище, виконуємо конкатенацію кількох рядків разом, що зробити
-- речення на основі переданих аргументів.
end
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 .. ' є моїм щасливим числом.' -- 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'.
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 'Самотній' -- 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 'Будьте позитивними!'
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.