Difference between revisions of "Module:Item"

From blackwiki
Jump to navigation Jump to search
blackwiki>Petr Matas
blackwiki>Petr Matas
Line 2: Line 2:
  
 
function escape(str)
 
function escape(str)
return str:gsub("([|\\])", "\\%1")
+
return str:gsub("[|\\]", function (c) return string.format("\\%03d", c:byte()) end)
 
end
 
end
  
 
function unescape(str)
 
function unescape(str)
return str:gsub("\\(.)", "%1")
+
return str:gsub("\\(%d%d%d)", function (d) return string.char(d) end)
 
end
 
end
  
 
function p.pack(frame)
 
function p.pack(frame)
 
local parent = frame:getParent()
 
local parent = frame:getParent()
 
 
local result = ''
 
local result = ''
 
for key, value in pairs(parent.args) do
 
for key, value in pairs(parent.args) do
 
result = result .. "|" .. escape(tostring(key)) .. "|" .. escape(value)
 
result = result .. "|" .. escape(tostring(key)) .. "|" .. escape(value)
 
end
 
end
 
 
return result .. "|";
 
return result .. "|";
 
end
 
end
  
 
function unpack(str)
 
function unpack(str)
+
local result = { }
 +
for key, value in str.gfind("|([^|]*)|([^|]*)") do
 +
result[unescape(key)] = unescape(value)
 +
end
 +
return result
 
end
 
end
  

Revision as of 05:03, 13 December 2015

This template implements {{Item}}, {{Component}} and {{Format item}}.


local p = {}

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

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

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

function p.each(frame)
	local parent = frame:getParent()
	local items = parent.args
	local separator = frame.args.separator or ""
	local template = frame.args.template
	
	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

return p