一.打印table
1 function PrintTable(tb) 2 if type(tb) ~= "table" then 3 print(tb) 4 return 5 end 6 7 local level = 0 8 local content = "" 9 10 local function GetSpace(level) 11 local spaceStr = "" 12 for i=1,level do 13 spaceStr = spaceStr .. " " 14 end 15 return spaceStr 16 end 17 18 local function GetString(value) 19 if type(value) ~= "string" then 20 return tostring(value) 21 else 22 return "\"" .. tostring(value) .. "\"" 23 end 24 end 25 26 local function PrintTb(tb, level) 27 level = level + 1 28 29 for k,v in pairs(tb) do 30 if type(k) == "table" then 31 content = content .. "\n" .. GetSpace(level) .. "{" 32 PrintTb(k, level) 33 content = content .. "\n" .. GetSpace(level) .. "} = " 34 else 35 content = content .. "\n" .. GetSpace(level) .. GetString(k) .. " = " 36 end 37 38 if type(v) == "table" then 39 content = content .. "{" 40 PrintTb(v, level) 41 content = content .. "\n" .. GetSpace(level) .. "}" 42 else 43 content = content .. GetString(v) 44 end 45 end 46 end 47 48 PrintTb(tb, level) 49 print("{" .. content .. "\n}") 50 end
测试1(嵌套table):
1 local x = 2 { 3 { 4 a = { 5 b = 20 6 }, 7 "asd", 8 }, 9 "30", 10 { 11 ["c"] = 40, 12 [6] = 50, 13 }, 14 }
输出:
测试2(key和value都是table):
1 local a = {10, [15] = 20, "30"} 2 local b = {a1 = "a1"} 3 local c = {} 4 c[a] = 2 5 c[b] = {b1 = 50}
输出:
二.复制table
1 function CloneTable(tb) 2 local clonedTable = {} --记录复制过的table,防止无限递归 3 local function CloneTb(tb) 4 if type(tb) ~= "table" then 5 return tb 6 elseif clonedTable[tb] then 7 return clonedTable[tb] 8 end 9 10 local newTb = {} 11 clonedTable[tb] = newTb 12 for key,value in pairs(tb) do 13 newTb[CloneTb(key)] = CloneTb(value) 14 end 15 return setmetatable(newTb, getmetatable(tb)) 16 end 17 return CloneTb(tb) 18 end
测试:
1 local a = {10, {a1 = "a1"}} 2 local b = CloneTable(a) 3 a[1] = "123" 4 a[2].a1 = 20 5 b[1] = "456" 6 PrintTable(a) 7 PrintTable(b)
输出: