Skylords Reborn
No edit summary
No edit summary
Line 14: Line 14:
 
local t
 
local t
 
local res = {}
 
local res = {}
  +
local next = next
   
 
if frame[1] or frame.name then
 
if frame[1] or frame.name then
 
t = frame
 
t = frame
elseif frame.args and (frame.args[1] or frame.args.name) then
+
elseif frame.args and next(frame.args) then
 
t = frame.args
 
t = frame.args
elseif frame:getParent() and (frame:getParent().args[1] or frame:getParent().args.name) then
+
elseif frame:getParent() and next(frame:getParent().args) then
 
t = frame:getParent().args
 
t = frame:getParent().args
 
end
 
end

Revision as of 10:50, 19 January 2021

Edit documentation

Description

Contains helper functions for use in other modules.

See also


local p = {}

---@param s string to format
---@return string|nil
function p.format(s, ...)
    local ran, val_or_err = pcall(string.format, s, ...)
    return ran and val_or_err or nil
end

--- converts input to arguments. returns itself, its arguments, its parent arguments or nil
---@param frame table input with arguments or the mw frame object
---@return table|nil argument list as table or nil
function p.getArgs(frame)
    local t
    local res = {}
    local next = next

    if frame[1] or frame.name then
        t = frame
    elseif frame.args and next(frame.args) then
        t = frame.args
    elseif frame:getParent() and next(frame:getParent().args) then
        t = frame:getParent().args
    end
    if t then
        for k, v in pairs(t) do
            if k and v then
                local key = type(k) == 'string' and k:gsub('%s+', '_') or k
                if type(v) == 'boolean' then
                    res[key] = v
                elseif tonumber(v) then
                    res[key] = tonumber(v)
                elseif type(v) == 'string' then
                    res[key] = mw.ustring.match(v, '^%s*(.*%S)') or ''
                    local value = res[key]:lower()
                    if mw.ustring.match(value, '%w') == nil or value == '' or value == 'default' then
                        res[key] = nil
                    elseif value == 'true' then
                        res[key] = true
                    elseif value == 'false' then
                        res[key] = false
                    end
                end
            end
        end
    end
    
    if next(res) == nil then return nil end
    return res
end

function p.split(str, sep)
	if not str or str == '' then return nil end
	local res = {}
	for m in (str..sep):gmatch("(.-)"..sep) do
		res[#res+1] = m
	end
	return #res == 0 and {str} or res
end

return p