Module:Road data/util
Appearance
| This module is rated as ready for general use. It has reached a mature state, is considered relatively stable and bug-free, and may be used wherever appropriate. It can be mentioned on help pages and other Wikipedia resources as an option for new users. To minimise server load and avoid disruptive output, improvements should be developed through sandbox testing rather than repeated trial-and-error editing. |
| This module is currently protected from editing. See the protection policy and protection log for more details. Please discuss any changes on the talk page; you may submit an edit request to ask an administrator to make an edit if it is uncontroversial or supported by consensus. You may also request that this page be unprotected. |
| This Lua module is used on approximately 42,000 pages and changes may be widely noticed. Test changes in the module's /sandbox or /testcases subpages, or in your own module sandbox. Consider discussing changes on the talk page before implementing them. |
Collection of utility functions for use within Module:Road data modules. See the code for function usages. Exported functions are: addAll and arrayToString.
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