forked from huuhghhgyg/Container-Terminal-Simulation
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtablestr.lua
73 lines (63 loc) · 1.94 KB
/
tablestr.lua
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
-- t: table
-- level: 最大显示table层级。不输入时处理为math.huge,即展开所有层级
function tablestr(t, level)
-- 非table类型直接返回
if type(t) ~= 'table' then
return tostring(t)
end
-- 检查level类型
if level == nil then
level = math.huge
elseif type(level) ~= "number" then
print(debug.traceback('TableString: level must be a number'))
os.exit()
elseif level < 0 then
print(debug.traceback('TableString: level must be a positive number'))
os.exit()
end
if level == 0 then
return '{...}'
end
-- 剩下table类型
local str = '{'
-- 迭代table中的内容
local keys = 0
local indices = 0
for k, v in pairs(t) do
if type(k) == 'number' then
-- 键值为index
if type(v) == 'table' then
str = str .. tablestr(v, level - 1)
elseif type(v) == 'function' then
str = str .. '(function)'
else
str = str .. tostring(v)
end
indices = indices + 1
else
-- 键值为key
if type(v) == 'table' then
str = str .. k .. '=' .. tablestr(v, level - 1)
elseif type(v) == 'function' then
str = str .. k .. '=' .. 'function()'
else
str = str .. k .. '=' .. tostring(v)
end
keys = keys + 1
end
str = str .. ', '
end
if indices + keys > 0 then
str = string.sub(str, 1, -3)
end
str = str .. '}'
return str
end
-- 示例代码
-- local collection = {'a',{1,2},{'hi', {'Anna', 'Bell', name='AnnaBell'}},{{'x','y','z'},{1,2,3}}}
-- local collection = {a='1',b='2', 'x', 'y', 'z', f=function() print('hi') end}
-- local collection = {1,2,3}
-- print(TableString('a'))
-- print(TableString(2))
-- print(TableString({}))
-- print(TableString(collection))