Created
November 10, 2013 19:17
-
-
Save ColonelThirtyTwo/7402531 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
local tinsert = table.insert | |
local tsort = table.sort | |
--- Recursively dumps a table's contents (sorted by the keys) to a file. | |
local function dumpTable(tbl, fname) | |
local out = assert(io.open(fname, "w")) | |
local visited = {} | |
local function sortKey(a,b) | |
local at, bt = type(a), type(b) | |
if at ~= bt then | |
return at < bt | |
elseif at == "number" or at == "string" then | |
return a < b | |
else | |
return tostring(a) < tostring(b) | |
end | |
end | |
local function dumpTableHelper(t, level) | |
local unvisited = {} | |
-- Make list of keys | |
local keys = {} | |
for k,v in pairs(t) do | |
if type(v) == "table" and not visited[v] then | |
visited[v] = true | |
unvisited[v] = true | |
end | |
tinsert(keys, k) | |
end | |
table.sort(keys, sortKey) | |
-- Go through each key, now sorted. | |
for _,k in ipairs(keys) do | |
local v = t[k] | |
for i=1,level do out:write("\t") end | |
out:write(tostring(k), " = ", tostring(v)) | |
if type(v) == "table" and unvisited[v] then | |
out:write(" {\n") | |
dumpTableHelper(v, level+1) | |
for i=1,level do out:write("\t") end | |
out:write("}") | |
unvisited[v] = nil | |
end | |
out:write(",\n") | |
end | |
end | |
dumpTableHelper(tbl, 0) | |
out:close() | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment