summaryrefslogtreecommitdiffstats
path: root/player
diff options
context:
space:
mode:
authorwm4 <wm4@nowhere>2014-04-11 00:33:38 +0200
committerwm4 <wm4@nowhere>2014-04-11 00:40:09 +0200
commit55d6e1f98d476edf488d65578d37ece7069d4ce4 (patch)
tree6233d8596ed4894b23f7c0c95db22a1b7508fbfa /player
parentfa35079361b18d147125c676b72a9b50a4057ebf (diff)
downloadmpv-55d6e1f98d476edf488d65578d37ece7069d4ce4.tar.bz2
mpv-55d6e1f98d476edf488d65578d37ece7069d4ce4.tar.xz
lua: add helper function for printing a table
Although this is something really basic, Lua's standard library doesn't provide anything like this. Probably because there are too many ways to do it right or wrong. This code tries to be really careful when dealing with mixed arrays/maps, e.g. when a table has integer keys starting from 1, making it look like an array, but then also has other keys.
Diffstat (limited to 'player')
-rw-r--r--player/lua/defaults.lua49
1 files changed, 49 insertions, 0 deletions
diff --git a/player/lua/defaults.lua b/player/lua/defaults.lua
index 4904e93b85..07d3a89ca1 100644
--- a/player/lua/defaults.lua
+++ b/player/lua/defaults.lua
@@ -373,4 +373,53 @@ function mp.osd_message(text, duration)
mp.commandv("show_text", text, duration)
end
+function mp.format_table(t, set)
+ if not set then
+ set = { [t] = true }
+ end
+ local res = "{"
+ -- pretty expensive but simple way to distinguish array and map parts of t
+ local keys = {}
+ local vals = {}
+ local arr = 0
+ for i = 1, #t do
+ if t[i] == nil then
+ break
+ end
+ keys[i] = i
+ vals[i] = t[i]
+ arr = i
+ end
+ for k, v in pairs(t) do
+ if not (type(k) == "number" and k >= 1 and k <= arr and keys[k]) then
+ keys[#keys + 1] = k
+ vals[#keys] = v
+ end
+ end
+ local function fmtval(v)
+ if type(v) == "string" then
+ return "\"" .. v .. "\""
+ elseif type(v) == "table" then
+ if set[v] then
+ return "[cycle]"
+ end
+ set[v] = true
+ return mp.format_table(v, set)
+ else
+ return tostring(v)
+ end
+ end
+ for i = 1, #keys do
+ if #res > 1 then
+ res = res .. ", "
+ end
+ if i > arr then
+ res = res .. fmtval(keys[i]) .. " = "
+ end
+ res = res .. fmtval(vals[i])
+ end
+ res = res .. "}"
+ return res
+end
+
return {}