forked from Liquipedia/Lua-Modules
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathformat_table.lua
More file actions
91 lines (77 loc) · 2.19 KB
/
Copy pathformat_table.lua
File metadata and controls
91 lines (77 loc) · 2.19 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
---
-- @Liquipedia
-- wiki=commons
-- page=Module:Format/Table
--
-- Please see https://github.com/Liquipedia/Lua-Modules to contribute
--
local Logic = require('Module:Logic')
local Table = require('Module:Table')
local TableFormatter = {}
function TableFormatter.toLuaCode(inputTable)
if type(inputTable) ~= 'table' then
error('TableFormatter.toLuaCode needs a table as input')
end
if Table.isEmpty(inputTable) then
return mw.html.create('pre')
:addClass('selectall')
:wikitext('{}')
end
local function escapeSingleQuote(str)
return str:gsub('\'', '\\\'')
end
local function displayValue(value)
if type(value) == 'string' then
return '\'' .. mw.text.nowiki(escapeSingleQuote(value)) .. '\''
else
return tostring(value)
end
end
local function order(_, key1, key2)
-- cases due to possibly having numbers and strings as keys
if Logic.isNumeric(key1) and Logic.isNumeric(key2) then
return key1 < key2
elseif Logic.isNumeric(key1) then
return true
elseif Logic.isNumeric(key2) then
return false
else -- 2 strings
return key1 < key2
end
end
local function toLuaString(tbl, indentNumber)
local luaString = '{'
for index, obj in ipairs(tbl) do
luaString = luaString .. '\n' .. string.rep('\t', indentNumber)
-- value display
if type(obj) == 'table' then
luaString = luaString .. toLuaString(obj, indentNumber + 1)
else
luaString = luaString .. displayValue(obj)
end
luaString = luaString .. ','
tbl[index] = nil
end
for key, obj in Table.iter.spairs(tbl, order) do
luaString = luaString .. '\n' .. string.rep('\t', indentNumber)
--key display
if type(key) == 'number' then
luaString = luaString .. '[' .. key .. '] = '
else
luaString = luaString .. '[\'' .. escapeSingleQuote(key) .. '\'] = '
end
-- value display
if type(obj) == 'table' then
luaString = luaString .. toLuaString(obj, indentNumber + 1)
else
luaString = luaString .. displayValue(obj)
end
luaString = luaString .. ','
end
return luaString .. '\n' .. string.rep('\t', indentNumber - 1) .. '}'
end
return mw.html.create('pre')
:addClass('selectall')
:wikitext(toLuaString(inputTable, 1))
end
return TableFormatter