Как вывести таблицу на консоль? - PullRequest
89 голосов
/ 07 февраля 2012

У меня проблемы с отображением содержимого таблицы, которая содержит вложенные таблицы (n-deep).Я хотел бы просто сбросить его на стандартный вывод или консоль с помощью оператора print или чего-то быстрого и грязного, но я не могу понять, как.Я ищу приблизительный эквивалент, который я получу при печати NSDictionary с использованием gdb.

Ответы [ 13 ]

1 голос
/ 07 февраля 2012

Боюсь, ты сам должен это закодировать. Я написал это, и это может быть полезным для вас

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
0 голосов
/ 15 апреля 2019

Добавление другой версии. Этот пытается итерировать и пользовательские данные.

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
0 голосов
/ 08 февраля 2019

Я использую свою собственную функцию для печати содержимого таблицы, но не уверен, насколько хорошо она соответствует вашей среде:

---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
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...