如何将表转储到控制台?

时间:2012-02-06 22:09:17

标签: lua

我在显示包含嵌套表(n-deep)的表的内容时遇到问题。我想通过print语句或快速而肮脏的东西将它转储到std out或控制台,但我无法弄清楚如何。我正在寻找使用gdb打印NSDictionary时得到的粗略等价物。

16 个答案:

答案 0 :(得分:82)

我知道这个问题已被标记为已回答,但让我在这里插入自己的库。它叫做inspect.lua,你可以在这里找到它:

https://github.com/kikito/inspect.lua

它只是一个文件,您可以从任何其他文件中获取。它返回一个函数,将任何Lua值转换为人类可读的字符串:

local inspect = require('inspect')

print(inspect({1,2,3})) -- {1, 2, 3}
print(inspect({a=1,b=2})
-- {
--   a = 1
--   b = 2
-- }

它正确缩进子表,并正确处理“递归表”(包含对自身的引用的表),因此它不会进入无限循环。它以合理的方式对价值进行排序。它还可以打印元信息。

问候!

答案 1 :(得分:47)

我发现这个有用。因为如果递归它也可以打印嵌套表。

function dump(o)
   if type(o) == 'table' then
      local s = '{ '
      for k,v in pairs(o) do
         if type(k) ~= 'number' then k = '"'..k..'"' end
         s = s .. '['..k..'] = ' .. dump(v) .. ','
      end
      return s .. '} '
   else
      return tostring(o)
   end
end

e.g。

local people = {
   {
      name = "Fred",
      address = "16 Long Street",
      phone = "123456"
   },

   {
      name = "Wilma",
      address = "16 Long Street",
      phone = "123456"
   },

   {
      name = "Barney",
      address = "17 Long Street",
      phone = "123457"
   }

}

print("People:", dump(people))

产生以下输出:

  

人物:{[1] = {["地址"] = 16长街,["电话"] =   123456,[" name"] = Fred,},[2] = {["地址"] = 16长   Street,[" phone"] = 123456,[" name"] = Wilma,},[3] = {["地址"] = 17   Long Street,[" phone"] = 123457,[" name"] = Barney,},}

答案 2 :(得分:46)

随意浏览Lua Wiki on table serialization。它列出了有关如何将表转储到控制台的几种方法。

你必须选择哪一个最适合你。有很多方法可以做到,但我通常最终使用Penlight中的那个:

> t = { a = { b = { c = "Hello world!", 1 }, 2, d = { 3 } } }
> require 'pl.pretty'.dump(t)
{
  a = {
    d = {
      3
    },
    b = {
      c = "Hello world!",
      1
    },
    2
  }
}

答案 3 :(得分:17)

发现了这个:

-- Print contents of `tbl`, with indentation.
-- `indent` sets the initial level of indentation.
function tprint (tbl, indent)
  if not indent then indent = 0 end
  for k, v in pairs(tbl) do
    formatting = string.rep("  ", indent) .. k .. ": "
    if type(v) == "table" then
      print(formatting)
      tprint(v, indent+1)
    elseif type(v) == 'boolean' then
      print(formatting .. tostring(v))      
    else
      print(formatting .. v)
    end
  end
end

从这里开始 https://gist.github.com/ripter/4270799

对我来说非常好......

答案 4 :(得分:8)

我见过的大多数纯lua打印表函数都存在深度递归问题 当走得太深时往往会导致堆栈溢出。这个印刷品 我写过的表函数没有这个问题。由于它处理串联的方式,它还应该能够处理非常大的表。在我个人使用这个功能时,它在大约一秒内输出了63k行文件。

输出还保持lua语法,并且可以轻松修改脚本 通过将输出写入文件(如果修改为允许)来实现简单的持久存储 只有要格式化的数字,布尔值,字符串和表数据类型。

function print_table(node)
    -- to make output beautiful
    local function tab(amt)
        local str = ""
        for i=1,amt do
            str = str .. "\t"
        end
        return str
    end

    local cache, stack, output = {},{},{}
    local depth = 1
    local output_str = "{\n"

    while true do
        local size = 0
        for k,v in pairs(node) do
            size = size + 1
        end

        local cur_index = 1
        for k,v in pairs(node) do
            if (cache[node] == nil) or (cur_index >= cache[node]) then

                if (string.find(output_str,"}",output_str:len())) then
                    output_str = output_str .. ",\n"
                elseif not (string.find(output_str,"\n",output_str:len())) then
                    output_str = output_str .. "\n"
                end

                -- This is necessary for working with HUGE tables otherwise we run out of memory using concat on huge strings
                table.insert(output,output_str)
                output_str = ""

                local key
                if (type(k) == "number" or type(k) == "boolean") then
                    key = "["..tostring(k).."]"
                else
                    key = "['"..tostring(k).."']"
                end

                if (type(v) == "number" or type(v) == "boolean") then
                    output_str = output_str .. tab(depth) .. key .. " = "..tostring(v)
                elseif (type(v) == "table") then
                    output_str = output_str .. tab(depth) .. key .. " = {\n"
                    table.insert(stack,node)
                    table.insert(stack,v)
                    cache[node] = cur_index+1
                    break
                else
                    output_str = output_str .. tab(depth) .. key .. " = '"..tostring(v).."'"
                end

                if (cur_index == size) then
                    output_str = output_str .. "\n" .. tab(depth-1) .. "}"
                else
                    output_str = output_str .. ","
                end
            else
                -- close the table
                if (cur_index == size) then
                    output_str = output_str .. "\n" .. tab(depth-1) .. "}"
                end
            end

            cur_index = cur_index + 1
        end

        if (size == 0) then
            output_str = output_str .. "\n" .. tab(depth-1) .. "}"
        end

        if (#stack > 0) then
            node = stack[#stack]
            stack[#stack] = nil
            depth = cache[node] == nil and depth + 1 or depth - 1
        else
            break
        end
    end

    -- This is necessary for working with HUGE tables otherwise we run out of memory using concat on huge strings
    table.insert(output,output_str)
    output_str = table.concat(output)

    print(output_str)
end

以下是一个例子:

local t = {
    ["abe"] = {1,2,3,4,5},
    "string1",
    50,
    ["depth1"] = { ["depth2"] = { ["depth3"] = { ["depth4"] = { ["depth5"] = { ["depth6"] = { ["depth7"]= { ["depth8"] = { ["depth9"] = { ["depth10"] = {1000}, 900}, 800},700},600},500}, 400 }, 300}, 200}, 100},
    ["ted"] = {true,false,"some text"},
    "string2",
    [function() return end] = function() return end,
    75
}

print_table(t)

输出:

{
    [1] = 'string1',
    [2] = 50,
    [3] = 'string2',
    [4] = 75,
    ['abe'] = {
        [1] = 1,
        [2] = 2,
        [3] = 3,
        [4] = 4,
        [5] = 5
    },
    ['function: 06472B70'] = 'function: 06472A98',
    ['depth1'] = {
        [1] = 100,
        ['depth2'] = {
            [1] = 200,
            ['depth3'] = {
                [1] = 300,
                ['depth4'] = {
                    [1] = 400,
                    ['depth5'] = {
                        [1] = 500,
                        ['depth6'] = {
                            [1] = 600,
                            ['depth7'] = {
                                [1] = 700,
                                ['depth8'] = {
                                    [1] = 800,
                                    ['depth9'] = {
                                        [1] = 900,
                                        ['depth10'] = {
                                            [1] = 1000
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
    },
    ['ted'] = {
        [1] = true,
        [2] = false,
        [3] = 'some text'
    }
}

答案 5 :(得分:4)

如前所述,你必须写它。 这是我的简陋版本:(超级基本版)

function tprint (t, s)
    for k, v in pairs(t) do
        local kfmt = '["' .. tostring(k) ..'"]'
        if type(k) ~= 'string' then
            kfmt = '[' .. k .. ']'
        end
        local vfmt = '"'.. tostring(v) ..'"'
        if type(v) == 'table' then
            tprint(v, (s or '')..kfmt)
        else
            if type(v) ~= 'string' then
                vfmt = tostring(v)
            end
            print(type(t)..(s or '')..kfmt..' = '..vfmt)
        end
    end
end

示例:

local mytbl = { ['1']="a", 2, 3, b="c", t={d=1} }
tprint(mytbl)

输出(Lua 5.0):

table[1] = 2
table[2] = 3
table["1"] = "a"
table["t"]["d"] = 1
table["b"] = "c"

答案 6 :(得分:2)

metalua table.tostring metehod实际上非常完整。它处理嵌套表,缩进级别是可变的,... 见https://github.com/fab13n/metalua/blob/master/src/lib/metalua/table2.lua

答案 7 :(得分:2)

这是我的版本,支持排除表格和用户数据

-- Lua Table View by Elertan
table.print = function(t, exclusions)
    local nests = 0
    if not exclusions then exclusions = {} end
    local recurse = function(t, recurse, exclusions)
        indent = function()
            for i = 1, nests do
                io.write("    ")
            end
        end
        local excluded = function(key)
            for k,v in pairs(exclusions) do
                if v == key then
                    return true
                end
            end
            return false
        end
        local isFirst = true
        for k,v in pairs(t) do
            if isFirst then
                indent()
                print("|")
                isFirst = false
            end
            if type(v) == "table" and not excluded(k) then
                indent()
                print("|-> "..k..": "..type(v))
                nests = nests + 1
                recurse(v, recurse, exclusions)
            elseif excluded(k) then
                indent()
                print("|-> "..k..": "..type(v))
            elseif type(v) == "userdata" or type(v) == "function" then
                indent()
                print("|-> "..k..": "..type(v))
            elseif type(v) == "string" then
                indent()
                print("|-> "..k..": ".."\""..v.."\"")
            else
                indent()
                print("|-> "..k..": "..v)
            end
        end
        nests = nests - 1
    end

    nests = 0
    print("### START TABLE ###")
    for k,v in pairs(t) do
        print("root")
        if type(v) == "table" then
            print("|-> "..k..": "..type(v))
            nests = nests + 1
            recurse(v, recurse, exclusions)
        elseif type(v) == "userdata" or type(v) == "function" then
            print("|-> "..k..": "..type(v))
        elseif type(v) == "string" then
            print("|-> "..k..": ".."\""..v.."\"")
        else
            print("|-> "..k..": "..v)
        end
    end
    print("### END TABLE ###")
end

这是一个例子

t = {
    location = {
       x = 10,
       y = 20
    },
    size = {
      width = 100000000,
      height = 1000,
    },
    name = "Sidney",
    test = {
        hi = "lol",
    },
    anotherone = {
        1, 
        2, 
        3
    }
}

table.print(t, { "test" })

打印:

   ### START TABLE ###
root
|-> size: table
    |
    |-> height: 1000
    |-> width: 100000000
root
|-> location: table
    |
    |-> y: 20
    |-> x: 10
root
|-> anotherone: table
    |
    |-> 1: 1
    |-> 2: 2
    |-> 3: 3
root
|-> test: table
    |
    |-> hi: "lol"
root
|-> name: "Sidney"
### END TABLE ###

请注意,根目录不会删除排除

答案 8 :(得分:1)

你必须自己编码我害怕。我写了这篇文章,它可能会对你有所帮助

function printtable(table, indent)

  indent = indent or 0;

  local keys = {};

  for k in pairs(table) do
    keys[#keys+1] = k;
    table.sort(keys, function(a, b)
      local ta, tb = type(a), type(b);
      if (ta ~= tb) then
        return ta < tb;
      else
        return a < b;
      end
    end);
  end

  print(string.rep('  ', indent)..'{');
  indent = indent + 1;
  for k, v in pairs(table) do

    local key = k;
    if (type(key) == 'string') then
      if not (string.match(key, '^[A-Za-z_][0-9A-Za-z_]*$')) then
        key = "['"..key.."']";
      end
    elseif (type(key) == 'number') then
      key = "["..key.."]";
    end

    if (type(v) == 'table') then
      if (next(v)) then
        printf("%s%s =", string.rep('  ', indent), tostring(key));
        printtable(v, indent);
      else
        printf("%s%s = {},", string.rep('  ', indent), tostring(key));
      end 
    elseif (type(v) == 'string') then
      printf("%s%s = %s,", string.rep('  ', indent), tostring(key), "'"..v.."'");
    else
      printf("%s%s = %s,", string.rep('  ', indent), tostring(key), tostring(v));
    end
  end
  indent = indent - 1;
  print(string.rep('  ', indent)..'}');
end

答案 9 :(得分:1)

--~ print a table
function printTable(list, i)

    local listString = ''
--~ begin of the list so write the {
    if not i then
        listString = listString .. '{'
    end

    i = i or 1
    local element = list[i]

--~ it may be the end of the list
    if not element then
        return listString .. '}'
    end
--~ if the element is a list too call it recursively
    if(type(element) == 'table') then
        listString = listString .. printTable(element)
    else
        listString = listString .. element
    end

    return listString .. ', ' .. printTable(list, i + 1)

end


local table = {1, 2, 3, 4, 5, {'a', 'b'}, {'G', 'F'}}
print(printTable(table))

嗨,伙计,我写了一个siple代码,在纯Lua中执行此操作,它有一个错误(在列表的最后一个元素之后写一个昏迷)但是我如何快速编写它作为原型我会让它适应你它符合您的需求。

答案 10 :(得分:1)

格式为 JSON (您可以&#34;美化&#34;稍后在IDE中):

let data = {
  "message": "The given data was invalid.",
  "errors": {
    "roomtype_id": [
      "Please select a room type"
    ],
    "price": [
      "Price cannot be empty"
    ],
    "amenities": [
      "Atleast select one amenities"
    ],
    "floor.0": [
      "Please select a floor"
    ],
    "floor.1": [
      "Please select a floor"
    ],
    "floor.2": [
      "Please select a floor"
    ],
    "floor.3": [
      "Please select a floor"
    ],
    "floor.4": [
      "Please select a floor"
    ],
    "room_number.0": [
      "Room number cannot be empty"
    ],
    "room_number.1": [
      "Room number cannot be empty"
    ],
    "room_number.2": [
      "Room number cannot be empty"
    ],
    "room_number.3": [
      "Room number cannot be empty"
    ],
    "room_number.4": [
      "Room number cannot be empty"
    ],
    "room_number.5": [
      "Room number cannot be empty"
    ],
    "room_number.6": [
      "Room number cannot be empty"
    ],
    "room_number.7": [
      "Room number cannot be empty"
    ],
    "room_number.8": [
      "Room number cannot be empty"
    ],
    "room_number.9": [
      "Room number cannot be empty"
    ],
    "room_number.10": [
      "Room number cannot be empty"
    ],
    "room_number.11": [
      "Room number cannot be empty"
    ],
    "room_number.12": [
      "Room number cannot be empty"
    ],
    "room_number.13": [
      "Room number cannot be empty"
    ],
    "room_number.14": [
      "Room number cannot be empty"
    ],
    "room_number.15": [
      "Room number cannot be empty"
    ],
    "room_number.16": [
      "Room number cannot be empty"
    ],
    "room_number.17": [
      "Room number cannot be empty"
    ],
    "room_number.18": [
      "Room number cannot be empty"
    ],
    "room_number.19": [
      "Room number cannot be empty"
    ],
    "room_number.20": [
      "Room number cannot be empty"
    ],
    "room_number.21": [
      "Room number cannot be empty"
    ],
    "room_number.22": [
      "Room number cannot be empty"
    ],
    "room_number.23": [
      "Room number cannot be empty"
    ],
    "room_number.24": [
      "Room number cannot be empty"
    ],
    "room_number.25": [
      "Room number cannot be empty"
    ],
    "room_number.26": [
      "Room number cannot be empty"
    ],
    "room_number.27": [
      "Room number cannot be empty"
    ],
    "room_number.28": [
      "Room number cannot be empty"
    ]
  }
}

let errorKeys = Object.keys(data.errors).filter(x => x.startsWith('floor'));

let count = errorKeys.length;

let floorErrors = errorKeys.map(key => ({
    key: key,
    errors: data.errors[key]
}));

console.log(errorKeys, count, floorErrors)

console.log()

用法:

local function format_any_value(obj, buffer)
    local _type = type(obj)
    if _type == "table" then
        buffer[#buffer + 1] = '{"'
        for key, value in next, obj, nil do
            buffer[#buffer + 1] = tostring(key) .. '":'
            format_any_value(value, buffer)
            buffer[#buffer + 1] = ',"'
        end
        buffer[#buffer] = '}' -- note the overwrite
    elseif _type == "string" then
        buffer[#buffer + 1] = '"' .. obj .. '"'
    elseif _type == "boolean" or _type == "number" then
        buffer[#buffer + 1] = tostring(obj)
    else
        buffer[#buffer + 1] = '"???' .. _type .. '???"'
    end
end

BTW,我还写了几个其他解决方案:非常快一个,还有一个特殊字符转义:https://github.com/vn971/fast_json_encode

答案 11 :(得分:1)

最简单的方法,具有循环引用处理和所有功能:

function dump(t, indent, done)
    done = done or {}
    indent = indent or 0

    done[t] = true

    for key, value in pairs(t) do
        print(string.rep("\t", indent))

        if (type(value) == "table" and not done[value]) then
            done[value] = true
            print(key, ":\n")

            dump(value, indent + 2, done)
            done[value] = nil
        else
            print(key, "\t=\t", value, "\n")
        end
    end
end

答案 12 :(得分:0)

我使用自己的函数来打印表的内容,但不确定如何将其转换为您的环境:

---A helper function to print a table's contents.
---@param tbl table @The table to print.
---@param depth number @The depth of sub-tables to traverse through and print.
---@param n number @Do NOT manually set this. This controls formatting through recursion.
function Lib:PrintTable(tbl, depth, n)
    n = n or 0;
    depth = depth or 5;

    if (depth == 0) then
        print(string.rep(' ', n).."...");
        return;
    end

    if (n == 0) then
        print(" ");
    end

    for key, value in pairs(tbl) do
        if (key and self:IsNumber(key) or self:IsString(key)) then
            key = string.format("[\"%s\"]", key);

            if (self:IsTable(value)) then
                if (next(value)) then
                    print(string.rep(' ', n)..key.." = {");
                    self:PrintTable(value, depth - 1, n + 4);
                    print(string.rep(' ', n).."},");
                else
                    print(string.rep(' ', n)..key.." = {},");
                end
            else
                if (self:IsString(value)) then
                    value = string.format("\"%s\"", value);
                else
                    value = tostring(value);
                end

                print(string.rep(' ', n)..key.." = "..value..",");
            end
        end
    end

    if (n == 0) then
        print(" ");
    end
end

答案 13 :(得分:0)

添加另一个版本。该尝试也可以遍历用户数据。

function inspect(o,indent)
    if indent == nil then indent = 0 end
    local indent_str = string.rep("    ", indent)
    local output_it = function(str)
        print(indent_str..str)
    end

    local length = 0

    local fu = function(k, v)
        length = length + 1
        if type(v) == "userdata" or type(v) == 'table' then
            output_it(indent_str.."["..k.."]")
            inspect(v, indent+1)
        else
            output_it(indent_str.."["..k.."] "..tostring(v))
        end
    end

    local loop_pairs = function()
        for k,v in pairs(o) do fu(k,v) end
    end

    local loop_metatable_pairs = function()
        for k,v in pairs(getmetatable(o)) do fu(k,v) end
    end

    if not pcall(loop_pairs) and not pcall(loop_metatable_pairs) then
        output_it(indent_str.."[[??]]")
    else
        if length == 0 then
            output_it(indent_str.."{}")
        end
    end
end

答案 14 :(得分:0)

lua 转储表的简单例子

我建议使用 serpent.lua

local function parser(value, indent, subcategory)
  local indent = indent or 2
  local response = '(\n'
  local subcategory = type(subcategory) == 'number' and subcategory or indent
  for key, value in pairs(value) do
    if type(value) == 'table' then
      value = parser(value, indent, subcategory + indent)

    elseif type(value) == 'string' then
      value = '\''.. value .. '\''

    elseif type(value) ~= 'number' then
      value = tostring(value)
    end

    if type(tonumber(key)) == 'number' then
        key = '[' .. key .. ']'
   elseif not key:match('^([A-Za-z_][A-Za-z0-9_]*)$') then
      key = '[\'' .. key .. '\']'
    end
    response = response .. string.rep(' ', subcategory) .. key .. ' = ' .. value .. ',\n'
  end
  return response .. string.rep(' ', subcategory - indent) .. ')'

end 

示例

response = parser{1,2,3, {ok = 10, {}}}
print(response)

结果

(
  [1] = 1,
  [2] = 2,
  [3] = 3,
  [4] = (
    [1] = (),
    ok = 10
  )
)

答案 15 :(得分:-1)

我谦虚地修改了一些Alundaio代码:

-- by Alundaio
-- KK modified 11/28/2019

function dump_table_to_string(node, tree, indentation)
    local cache, stack, output = {},{},{}
    local depth = 1


    if type(node) ~= "table" then
        return "only table type is supported, got " .. type(node)
    end

    if nil == indentation then indentation = 1 end

    local NEW_LINE = "\n"
    local TAB_CHAR = " "

    if nil == tree then
        NEW_LINE = "\n"
    elseif not tree then
        NEW_LINE = ""
        TAB_CHAR = ""
    end

    local output_str = "{" .. NEW_LINE

    while true do
        local size = 0
        for k,v in pairs(node) do
            size = size + 1
        end

        local cur_index = 1
        for k,v in pairs(node) do
            if (cache[node] == nil) or (cur_index >= cache[node]) then

                if (string.find(output_str,"}",output_str:len())) then
                    output_str = output_str .. "," .. NEW_LINE
                elseif not (string.find(output_str,NEW_LINE,output_str:len())) then
                    output_str = output_str .. NEW_LINE
                end

                -- This is necessary for working with HUGE tables otherwise we run out of memory using concat on huge strings
                table.insert(output,output_str)
                output_str = ""

                local key
                if (type(k) == "number" or type(k) == "boolean") then
                    key = "["..tostring(k).."]"
                else
                    key = "['"..tostring(k).."']"
                end

                if (type(v) == "number" or type(v) == "boolean") then
                    output_str = output_str .. string.rep(TAB_CHAR,depth*indentation) .. key .. " = "..tostring(v)
                elseif (type(v) == "table") then
                    output_str = output_str .. string.rep(TAB_CHAR,depth*indentation) .. key .. " = {" .. NEW_LINE
                    table.insert(stack,node)
                    table.insert(stack,v)
                    cache[node] = cur_index+1
                    break
                else
                    output_str = output_str .. string.rep(TAB_CHAR,depth*indentation) .. key .. " = '"..tostring(v).."'"
                end

                if (cur_index == size) then
                    output_str = output_str .. NEW_LINE .. string.rep(TAB_CHAR,(depth-1)*indentation) .. "}"
                else
                    output_str = output_str .. ","
                end
            else
                -- close the table
                if (cur_index == size) then
                    output_str = output_str .. NEW_LINE .. string.rep(TAB_CHAR,(depth-1)*indentation) .. "}"
                end
            end

            cur_index = cur_index + 1
        end

        if (size == 0) then
            output_str = output_str .. NEW_LINE .. string.rep(TAB_CHAR,(depth-1)*indentation) .. "}"
        end

        if (#stack > 0) then
            node = stack[#stack]
            stack[#stack] = nil
            depth = cache[node] == nil and depth + 1 or depth - 1
        else
            break
        end
    end

    -- This is necessary for working with HUGE tables otherwise we run out of memory using concat on huge strings
    table.insert(output,output_str)
    output_str = table.concat(output)

    return output_str

end

然后:

print(dump_table_to_string("AA", true,3))

print(dump_table_to_string({"AA","BB"}, true,3))

print(dump_table_to_string({"AA","BB"}))

print(dump_table_to_string({"AA","BB"},false))

print(dump_table_to_string({"AA","BB",{22,33}},true,2))

给予:

only table type is supported, got string

{
   [1] = 'AA',
   [2] = 'BB'
}

{
 [1] = 'AA',
 [2] = 'BB'
}

{[1] = 'AA',[2] = 'BB'}

{
  [1] = 'AA',
  [2] = 'BB',
  [3] = {
    [1] = 22,
    [2] = 33
  }
}