Module:Repr
This module contains functions for generating string representations of Lua objects. It is inspired by Python's repr function.
Usage
To use the module, first you have to import it.
local mRepr = require("Module:Repr")
Then you can use the functions it contains. The documentation for each function is below.
repr
This function generates a string representation of any given Lua object. The idea is that if you copy the string this function produces it, and paste it back into a Lua program, then you should be able to reproduce the original object. This doesn't work for all values, but it should hold for simple cases.
For example, mRepr.repr({bool = true, number = 6, str = "hello world"})
will output the string {bool = true, number = 6, str = "hello world"}
.
Basic syntax:
mRepr.repr(value)
Full syntax:
mRepr.repr(value, options)
Parameters:
value
: The value to convert to a string. This can be any Lua value. This parameter is optional, and defaults tonil
.options
: A table of options. This parameter is optional.
The following options can be specified in the options table:
pretty
: If true, output the string in "pretty" format (as in pretty-printing). This will add new lines and indentation between table items. If false, format everything on one line. The default is false.tabs
: If true, indent with tabs; otherwise, indent with spaces. The default is true. This only has an effect ifpretty
is true.spaces
: The number of spaces to indent with, iftabs
is false. The default is 4. This only has an effect ifpretty
is true.semicolons
: If true, table items are separated with semicolons. If false, they are separated with spaces. The default is false.sortKeys
: If true, sort table keys in lexical order, after other table key formatting has been applied (such as adding square brackets). If false, table keys are output in arbitrary order (the order they are processed by the pairs function). The default is true.depth
: The indentation depth to output the top-level object at. The default is 0. This only has an effect ifpretty
is true.
Features:
- The function handles cyclic tables gracefully; when it detects a cycle, the inner table is rendered as
{CYCLIC}
. __tostring
metamethods are automatically called if they are available.- The sequence part of a table is always rendered as a sequence. If there are also key-value pairs, they will be rendered after the sequence part.
Here is an example that shows off all the bells and whistles:
local myTable = {
hello = "repr",
usefulness = 100,
isEasyToUse = true,
sequence = {"a", "sequence", "table"},
mixed = {"a", "sequence", with = "key-value pairs"},
subTables = {
moreInfo = "Calls itself recursively on sub-tables"
},
usesToString = setmetatable({}, {__tostring = function () return "__tostring functions are called automatically" end}),
["$YMBOL$"] = "Keys that aren't Lua identifiers are quoted";
[{also = "Tables as keys work too";}] = "in case you need that",
cyclic = {note = "cyclical tables are printed as just {CYCLIC}"}
}
myTable.cyclic.cyclic = myTable.cyclic -- Create a cycle
local options = {
pretty = true, -- print with \n and indentation?
semicolons = false, -- when printing tables, use semicolons (;) instead of commas (,)?
sortKeys = true, -- when printing dictionary tables, sort keys alphabetically?
spaces = 3, -- when pretty printing, use how many spaces to indent?
tabs = false, -- when pretty printing, use tabs instead of spaces?
depth = 0, -- when pretty pretty printing, what level to start indenting at?
}
mw.log(mRepr.repr(myTable, options))
This logs the following:
{ ["$YMBOL$"] = "Keys that aren't Lua identifiers are quoted", [{ also = "Tables as keys work too" }] = "in case you need that", cyclic = { cyclic = {CYCLIC}, note = "cyclical tables are printed as just {CYCLIC}" }, hello = "repr", isEasyToUse = true, mixed = { "a", "sequence", with = "key-value pairs" }, sequence = { "a", "sequence", "table" }, subTables = { moreInfo = "Calls itself recursively on sub-tables" }, usefulness = 100, usesToString = __tostring functions are called automatically }
invocationRepr
This function generates a string representation of a function invocation.
Basic syntax:
mRepr.invocationRepr{funcName = functionName, args = functionArgs}
Full syntax:
mRepr.invocationRepr{funcName = functionName, args = functionArgs, options = options}
Parameters:
funcName
: The function name. This parameter is required, and must be a string.args
: The function arguments. This should be sequence table. The sequence items can be any Lua value, and will each be rendered using the [[#repr|]] function. This argument is optional.options
: A table of options. The options are the same as for the repr function. This argument is optional.
Examples:
mRepr.invocationRepr{funcName = "myFunc", args = {"test", 4, true, {"a", "b", "c"}}}
Result: myFunc("test", 4, true, {"a", "b", "c"})
local defaultSettings = {
pretty = false;
tabs = true;
semicolons = false;
spaces = 4;
sortKeys = true;
}
-- lua keywords
local keywords = {
["and"] = true,
["break"] = true,
["do"] = true,
["else"] = true,
["elseif"] = true,
["end"] = true,
["false"] = true,
["for"] = true,
["function"] = true,
["if"] = true,
["in"] = true,
["local"] = true,
["nil"] = true,
["not"] = true,
["or"] = true,
["repeat"] = true,
["return"] = true,
["then"] = true,
["true"] = true,
["until"] = true,
["while"] = true,
}
local function isLuaIdentifier(str)
return type(str) == "string"
-- must be nonempty
and str:len() > 0
-- can only contain a-z, A-Z, 0-9 and underscore
and not str:find("[^%d%a_]")
-- cannot begin with digit
and not tonumber(str:sub(1, 1))
-- cannot be keyword
and not keywords[str]
end
local function reprRecursive(value, reprSettings, indent, depth, shown)
local v = value
if type(v) == "string" then
return (("%q"):format(v):gsub("\\\n", "\\n"))
elseif type(v) == "number" then
if v == math.huge then return "math.huge" end
if v == -math.huge then return "-math.huge" end
return tostring(tonumber(v))
elseif type(v) == "boolean" then
return tostring(v)
elseif type(v) == "nil" then
return "nil"
elseif type(v) == "table" and getmetatable(v) and type(getmetatable(v).__tostring) == "function" then
return tostring(getmetatable(v).__tostring(v))
elseif type(v) == "table" then
if shown[v] then return "{CYCLIC}" end
shown[v] = true
local tabs = indent:rep(depth)
local str = "{" .. (reprSettings.pretty and ("\n" .. indent .. tabs) or "")
local isArray = true
for k, v in pairs(v) do
if type(k) ~= "number" or k < 1 or k == math.huge or k ~= math.floor(k) then
isArray = false
break
end
end
if isArray then
for i = 1, #v do
if i ~= 1 then
str = str .. (reprSettings.semicolons and ";" or ",") .. (reprSettings.pretty and ("\n" .. indent .. tabs) or " ")
end
depth = depth + 1
str = str .. reprRecursive(v[i], reprSettings, indent, depth, shown)
depth = depth - 1
end
else
local keyOrder = {}
local keyValueStrings = {}
for k, v in pairs(v) do
depth = depth + 1
local kStr = isLuaIdentifier(k) and k or ("[" .. reprRecursive(k, reprSettings, indent, depth, shown) .. "]")
local vStr = reprRecursive(v, reprSettings, indent, depth, shown)
table.insert(keyOrder, kStr)
keyValueStrings[kStr] = vStr
depth = depth - 1
end
if reprSettings.sortKeys then table.sort(keyOrder) end
local first = true
for _, kStr in pairs(keyOrder) do
if not first then
str = str .. (reprSettings.semicolons and ";" or ",") .. (reprSettings.pretty and ("\n" .. indent .. tabs) or " ")
end
str = str .. ("%s = %s"):format(kStr, keyValueStrings[kStr])
first = false
end
end
shown[v] = false
if reprSettings.pretty then
str = str .. "\n" .. tabs
end
str = str .. "}"
return str
else
return "<" .. type(v) .. ">"
end
end
local function repr(value, reprSettings)
reprSettings = reprSettings or {}
for setting, settingValue in pairs(defaultSettings) do
if reprSettings[setting] == nil then
reprSettings[setting] = defaultSettings[setting]
end
end
local indent = (" "):rep(reprSettings.spaces or defaultSettings.spaces)
if reprSettings.tabs then
indent = "\t"
end
local depth = 0
local shown = {}
return reprRecursive(value, reprSettings, indent, depth, shown)
end
return {
isLuaIdentifier = isLuaIdentifier,
repr = repr,
}