Jump to content

Module:Road data/util

From Simple English Wikipedia, the free encyclopedia
Revision as of 00:48, 30 April 2016 by imported>Chinissai (Created page with 'local util = {} local format = mw.ustring.format --- -- Add all entries in `arr` into `target`. -- An error is raised if any key in `arr` is already in `target...')
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)

Documentation for this module may be created at Module:Road data/util/doc

local util = {}

local format = mw.ustring.format

---
-- Add all entries in `arr` into `target`.
-- An error is raised if any key in `arr` is already in `target`.
function util.addAll(target, arr)
	for key,value in pairs(arr) do
		if target[key] == nil then
			target[key] = value
		else
			error("Duplicate key: " .. tostring(key))
		end
	end
end

local function comp(e1, e2)
	local t1 = type(e1)
	local t2 = type(e2)
	if t1 ~= t2 then return t1 < t2 end
	return e1 < e2
end

local arrayToStringAux
arrayToStringAux = function(arr, indent)
	local result = {}
	local keys = {}
	for key in pairs(arr) do table.insert(keys, key) end
	table.sort(keys, comp)
	for _,key in ipairs(keys) do
		local value = arr[key]
		local keyPrint
		if type(key) == "string" then
			keyPrint = format("\"%s\"", key)
		else
			keyPrint = tostring(key)
		end
		local valuePrint
		if type(value) == "table" then
			valuePrint = format("{\n%s\n%s}", arrayToStringAux(value, indent + 4), string.rep(" ", indent))
		elseif type(value) == "string" then
			valuePrint = format("\"%s\"", value)
		else
			valuePrint = tostring(value)
		end
		table.insert(result, format("%s[%s] = %s", string.rep(" ", indent), keyPrint, valuePrint))
	end
	return table.concat(result, ", \n")
end

--- Return a string representation of `arr`.
function util.arrayToString(arr, indent)
	return arrayToStringAux(arr, indent or 0)
end

return util