lua的打印写了一边又一边,我去,每次都要考虑一下,花写时间去写,这个有点,那个啥,扔这里
local string_format = string.format;
local table_insert = table.insert;
function dump_r(t)
local sp = " ";
local function do_print(tt, l)
local tp = type(tt);
if (tp == "table") then
l = l + 1;
if (l - 1 == 0) then
print("{");
end
for k, v in pairs(tt) do
local pp = type(v);
if (pp == "table") then
print(string_format("%"..l.."s[%s]={",sp,k));
do_print(v, l + 1);
print(string_format("%"..l.."s},",sp));
else
print(string_format("%"..l.."s[%s]=%s,",sp,k,tostring(v)));
end
end
if (l - 1 == 0) then
print("}");
end
else
print(string_format("%"..l.."s=%s,",sp,k,tostring(tt)));
end
end
do_print(t, 0);
end
function dump_tostring(t)
local sp = " ";
local list = {};
local function addline(str)
table_insert(list, str);
end
local function do_tostring(tt, l, ln)
local tp = type(tt);
if (tp == "table") then
l = l + 1;
if (l - 1 == 0) then
addline("{");
end
for k, v in pairs(tt) do
local pp = type(v);
if (pp == "table") then
addline(string_format("%"..l.."s[%s]={",sp,k));
do_tostring(v, l + 1);
addline(string_format("%"..l.."s},",sp));
else
addline(string_format("%"..l.."s[%s]=%s,",sp,k,tostring(v)));
end
end
if (l - 1 == 0) then
addline("}");
end
else
addline(string_format("%"..l.."s=%s,",sp,k,tostring(tt)));
end
end
do_tostring(t, 0);
return table.concat(list, "\n");
end
local kt = {
ss = "33";
mm = "39";
ks = {
mk = 36;
sk = {1,2,3,4,5};
}
}
print("===========");
--dump_r(kt);
local s = dump_tostring(kt);
print(s);