首页 > 代码库 > 递归打印lua中的table

递归打印lua中的table

递归打印lua中的table,并写到文件里:

  1 local pairs_by_keys = function(inTable)  2     local temp = {}  3     for k, v in pairs(inTable) do  4         temp[#temp + 1] = k  5     end  6   7     local compare = function(a, b)  8         if type(a) == type(b) then  9             return a < b 10         elseif type(a) == "number" then 11             return true 12         else 13             return false 14         end 15     end 16  17     table.sort(temp, compare) 18  19     local i = 0 20     return function() 21         i = i + 1 22         return temp[i], inTable[temp[i]] 23     end 24 end 25  26 local get_space_string = function(n) 27     n = n or 0 28     return string.rep("    ", n)  29 end 30  31 ----------------------------------------------------- 32 local write_table_head = function(tableName, writer) 33     if writer then 34         tableName = tableName or "gdTable" 35         writer("if not(type(" .. tableName .. ") == \"table\") then\n") 36         writer("    " .. tableName .. " = {}\n") 37         writer("end\n\n") 38     end 39 end 40  41 local function write_table_body(tableName, inTable, writer, deep) 42     if inTable and writer then 43         tableName = tableName or "gdTable" 44         deep = deep or 0 45  46         local space = get_space_string(deep) 47  48         -- head 49         writer(space .. tableName .. " = {\n") 50  51         -- body 52         local spaceEx = get_space_string(deep + 1) 53         for k, v in pairs_by_keys(inTable) do 54             if type(k) == "number" then 55                 k = "[" .. k .. "]" 56             end 57  58             if type(v) == "table" then 59                 write_table_body(k, v, writer, deep + 1) 60             elseif type(v) == "string" then 61                 writer(spaceEx .. k .. " = \"" .. v .. "\",\n") 62             else 63                 writer(spaceEx .. k .. " = " .. tostring(v) .. ",\n") 64             end 65         end 66  67         -- tail 68         if deep > 0 then 69             writer(space .. "},\n") 70         else 71             writer(space .. "}\n") 72         end 73     end 74 end 75  76 ---------------------------------------------------------- 77 -- interface 78 -- 79 write_table = function(inTable, tableName, filePath) 80     local file = io.open(filePath, "w") 81     if file then 82         local writer = function(s) 83             file:write(s) 84         end 85         write_table_head(tableName, writer) 86         write_table_body(tableName, inTable, writer) 87         file:close() 88     end 89 end 90  91 ---------------------------------------------------------- 92 -- test 93 -- 94 local test = { 95     [3] = 3, 96     [1] = 1, 97     b = "b", 98     [2] = 2, 99     a = "a",100     sub = {101         b = true,102         [1] = "x",103     },104 }105 106 write_table(test, "test", "out.lua")

 

递归打印lua中的table