一.打印table
function PrintTable(tb)
if type(tb) ~= "table" then
print(tb)
return
end local level =
local content = "" local function GetSpace(level)
local spaceStr = ""
for i=,level do
spaceStr = spaceStr .. " "
end
return spaceStr
end local function GetString(value)
if type(value) ~= "string" then
return tostring(value)
else
return "\"" .. tostring(value) .. "\""
end
end local function PrintTb(tb, level)
level = level + for k,v in pairs(tb) do
if type(k) == "table" then
content = content .. "\n" .. GetSpace(level) .. "{"
PrintTb(k, level)
content = content .. "\n" .. GetSpace(level) .. "} = "
else
content = content .. "\n" .. GetSpace(level) .. GetString(k) .. " = "
end if type(v) == "table" then
content = content .. "{"
PrintTb(v, level)
content = content .. "\n" .. GetSpace(level) .. "}"
else
content = content .. GetString(v)
end
end
end PrintTb(tb, level)
print("{" .. content .. "\n}")
end
测试1(嵌套table):
local x =
{
{
a = {
b =
},
"asd",
},
"",
{
["c"] = ,
[] = ,
},
}
输出:文章来源地址:https://www.yii666.com/article/758208.html
测试2(key和value都是table):文章地址https://www.yii666.com/article/758208.html
local a = {, [] = , ""}
local b = {a1 = "a1"}
local c = {}
c[a] =
c[b] = {b1 = }
输出:网址:yii666.com
二.复制table
function CloneTable(tb)
local clonedTable = {} --记录复制过的table,防止无限递归
local function CloneTb(tb)
if type(tb) ~= "table" then
return tb
elseif clonedTable[tb] then
return clonedTable[tb]
end local newTb = {}
clonedTable[tb] = newTb
for key,value in pairs(tb) do
newTb[CloneTb(key)] = CloneTb(value)
end
return setmetatable(newTb, getmetatable(tb))
end
return CloneTb(tb)
end
测试:
local a = {, {a1 = "a1"}}
local b = CloneTable(a)
a[] = ""
a[].a1 =
b[] = ""
PrintTable(a)
PrintTable(b)
输出: