Hi,
I created a function to return a table as a nice formatted string.
I also included an iterator to sort the table.
Lua
function PairsByKeys(t, f)
------------------------------------------------------------------------------
-- Returns an iterator that traverses a table following the order of its keys
-- t Table
-- f Comparison function (optional)
-- See GetTableString
------------------------------------------------------------------------------
-- AssertTable(t)
-- if f then AssertFunction(f) end
------------------------------------------------------------------------------
local a = {}
for n in pairs(t) do table.insert(a, n) end
table.sort(a, f)
local i = 0 -- iterator variable
local iter = -- iterator function
function ()
i = i + 1
if a[i] == nil then return nil else return a[i], t[a[i]] end
end
return iter
end
function GetTableString(t, full)
------------------------------------------------------------------------------
-- Return table t as printable string "{key = value, ...}", sorted on key
-- t Table
-- full Boolean (optional, if true then print all keys)
------------------------------------------------------------------------------
-- AssertTable(t)
-- if full then AssertBoolean(full) end
------------------------------------------------------------------------------
local s, svalue
local f = function(a, b) return tostring(a) < tostring(b) end
local p = function(f, t) end
if not full and IsArray(t) then p = pairs else p = PairsByKeys end
for key, value in p(t, f) do
if s then s = s..", " else s = "" end
if type(value) == "nil" then
svalue = type(value)
elseif type(value) == "boolean" then
svalue = tostring(value)
elseif type(value) == "number" then
svalue = tostring(value)
elseif type(value) == "string" then
svalue = "'"..value.."'"
elseif type(value) == "userdata" then
svalue = type(value)
elseif type(value) == "function" then
svalue = type(value)
elseif type(value) == "thread" then
svalue = type(value)
elseif type(value) == "table" then
svalue = GetTableString(value, full) -- recursive !!
else
svalue = type(value).."???"
end
if not full and IsArray(t) then
s = s..svalue
else
s = s..key.." = "..svalue
end
end
if not s then s = "" end
return "{"..s.."}"
end
Alles anzeigen