From 55d6e1f98d476edf488d65578d37ece7069d4ce4 Mon Sep 17 00:00:00 2001 From: wm4 Date: Fri, 11 Apr 2014 00:33:38 +0200 Subject: 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. --- player/lua/defaults.lua | 49 +++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 49 insertions(+) (limited to 'player/lua/defaults.lua') 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 {} -- cgit v1.2.3