See Global Lua Modules/Comma
local p = {}
local i18n = require('Dev:i18n').loadMessages('Comma')
local getArgs = require('Dev:Arguments').getArgs
local trim = mw.text.trim
local function validateTable(items)
local output = {}
for _,v in ipairs(items) do
if type(v) == 'string' and trim(v) ~= '' then
output[#output + 1] = trim(v)
elseif type(v) == 'number' then
output[#output + 1] = v
end
end
return output
end
function p.main(args, opt)
opt = opt or {}
local items = validateTable(args)
local output = ''
local penultimate = ''
local tailender = ''
-- separators
local comma = opt['sep1'] and opt['sep1'] or i18n:msg('sep1')
local sep2
local sep3
if opt.useAnd then
sep2 = opt['sep2'] or i18n:msg('sep2and')
sep3 = opt['sep3'] or i18n:msg('sep3and')
else
sep2 = opt['sep2'] or i18n:msg('sep2or')
sep3 = opt['sep3'] or i18n:msg('sep3or')
end
for _, v in ipairs(items) do
if output ~= '' then
output = output .. comma
end
output = output .. penultimate
-- shift
penultimate = tailender
tailender = v
end
-- add penultimate and tailender to the output
if output ~= '' then
-- 3 or more items in total
output = output .. comma .. penultimate .. sep3 .. tailender
else
if penultimate ~= '' then
-- 2 items
output = penultimate .. sep2 .. tailender
else
-- 1 item
output = tailender
end
end
return output
end
function p._main(frame)
local args = getArgs(frame)
local opt = {
useAnd = (args['and'] and trim(args['and']) ~= '') and true or false,
sep1 = (args['sep1'] and trim(args['sep1']) ~= '') and args['sep1'] or nil,
sep2 = (args['sep2'] and trim(args['sep2']) ~= '') and args['sep2'] or nil,
sep3 = (args['sep3'] and trim(args['sep3']) ~= '') and args['sep3'] or nil
}
return p.main(args, opt)
end
return p