Module:Item

From escforumwiki
Revision as of 05:20, 14 December 2015 by en>Petr Matas (+ format)
Jump to navigation Jump to search

Documentation for this module may be created at Module:Item/doc

local p = {}

local function escape(str)
	return str:gsub("[|\\]", function (c) return string.format("\\%03d", c:byte()) end)
end

local function unescape(str)
	return str:gsub("\\(%d%d%d)", function (d) return string.char(d) end)
end

function p.pack(frame)
	local parent = frame:getParent()
	local result = ''
	for key, value in pairs(parent.args) do
		result = result .. "|" .. escape(tostring(key)) .. "|" .. escape(value)
	end
	return result .. "|";
end

local function unpack(str)
	local result = { }
	for key, value in str:gfind("|([^|]*)|([^|]*)") do
		result[unescape(key)] = unescape(value)
	end
	return result
end

function p.component(frame)
	return unpack(frame.args[1])[frame.args[2]]
end

local function getItems(frame)
	return frame:getParent().args
end

local function getTemplate(frame)
	return frame.args.template
end

function p.format(frame)
	local args = frame:getParent().args
	local templateArgs = unpack(args.item)
	
	for key, value in pairs(args) do
		if key ~= "template" and key ~= "item" then
			local _, _, paramKey = string.find(key, "^param (.*)")
			local _, _, importantKey = string.find(key, "^important (.*)")
			paramKey = paramKey or importantKey or key
			if importantKey or templateArgs[paramKey] == nil then
				templateArgs[paramKey] = value
			end
		end
	end
	
	return frame:expandTemplate{ title = args.template, args = templateArgs }
end

function p.each(frame)
	local items = getItems(frame)
	local separator = frame.args[1] or ""
	local template = getTemplate(frame)
	
	local result = ""
	for i, item in ipairs(items) do
		result = result .. frame:expandTemplate{ title = template, args = unpack(item) }
		if items[i + 1] then
			result = result .. separator
		end
	end
	return result
end

function p.gather(frame)
	local items = getItems(frame)
	local template = getTemplate(frame)
	local parameter = frame.args.parameter or "1"
	
	local args = { }
	for i, item in ipairs(items) do
		args[i] = unpack(item)[parameter]
	end
	
	return frame:expandTemplate{ title = template, args = args }
end

return p