-- Some useful Lua functions. util = {} function util.key_ordered_pairs(t, f) local a = {} for n in pairs(t) do table.insert(a, n) end table.sort(a, f) local i = 0 local iter = function () i = i + 1 if a[i] == nil then return nil else return a[i], t[a[i]] end end return iter end local function write_imp(name, t, file, indent) for i = 1, indent do file:write("\t") end local ty = type(t) if name then file:write(string.format("%s = ", name)) end if ty == 'table' then file:write("{\n") local del = false if #t > 0 then for i, v in ipairs(t) do write_imp(nil, v, file, indent + 1) file:write(',\n') end del = true else for k, v in util.key_ordered_pairs(t) do write_imp(tostring(k), v, file, indent + 1) file:write(',\n') del = true end end if del then file:seek('cur', -2) -- Wipe the last comma end file:write('\n') for i = 1, indent do file:write("\t") end file:write("}") elseif ty == 'string' then file:write(string.format("'%s'", t)) else file:write(string.format("%s", tostring(t))) end end function util.write_table(kname, t, fname) local file = io.open(fname, 'w') write_imp(kname, t, file, 0) end function util.deep_copy(tab) local r = {} for k, v in pairs(tab) do local nv if type(v) == 'table' then nv = util.deep_copy(v) else nv = v end r[k] = nv end return r end