Skip to content

Instantly share code, notes, and snippets.

@Asmageddon
Last active Aug 29, 2015
Embed
What would you like to do?
Lua util functions - pretty-printing, defaultdict, etc.
Just some Lua snippets.
function defaultdict(default_value_factory)
local mt = {
__index = function(t, key)
if not rawget(t, key) then
rawset(t, key, default_value_factory())
end
return rawget(t, key)
end
}
return setmetatable({}, mt)
end
local function setup_pairs()
local t = setmetatable({}, {
__pairs=function(t)
return pairs({x = 4, y = 6})
end
})
for k,v in pairs(t) do return end
rawpairs = pairs
function pairs(t)
local mt = getmetatable(t)
return (mt and mt.__pairs or rawpairs)(t)
end
end
local function setup_ipairs()
local t = setmetatable({}, {
__ipairs=function(t)
return pairs({x = 4, y = 6})
end
})
for k,v in ipairs(t) do return end
rawipairs = ipairs
function ipairs(t)
local mt = getmetatable(t)
return (mt and mt.__ipairs or rawipairs)(t)
end
end
setup_pairs()
setup_ipairs()
function str(obj, pretty_mode, max_depth, _depth, _visited)
max_depth = max_depth or -1
_depth = _depth or 1
_visited = _visited and setmetatable({}, {__index = _visited}) or {}
pretty_mode = pretty_mode or false
local obj_type = type(obj)
if obj_type == "string" then
return '"' .. obj .. '"'
elseif obj_type == "table" and _visited[obj] ~= nil and _visited[obj] ~= _depth then
return "<loop>"
elseif obj_type == "table" and (max_depth < 0 or _depth <= max_depth) then
_visited[obj] = true
local result = "{"
if pretty_mode then result = result .. "\n"; end
local indent = pretty_mode and string.rep(" ", _depth) or ""
local prev_indent = pretty_mode and string.rep(" ", _depth-1) or ""
for k, v in ipairs(obj) do
result = result .. indent .. str(v, pretty_mode, max_depth, _depth + 1, _visited) .. ", "
if pretty_mode then result = result .. "\n"; end
end
for k, v in pairs(obj) do
if type(k) ~= "number" or not (k >= 1 and k <= #obj) then
result = result .. indent .. tostring(k) .. " = " .. str(v, pretty_mode, max_depth, _depth + 1, _visited) .. ", "
if pretty_mode then result = result .. "\n"; end
end
end
result = result .. prev_indent .. "}"
return result
elseif obj_type == "number" or obj_type == "nil" then
return tostring(obj)
elseif obj_type == "boolean" then
return "[" .. tostring(obj) .. "]"
else
return "<" .. (tostring(obj) or "userdata/unknown") .. ">"
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment