HenryEx icon

Print table to LUA console

HenryEx | PRO | 08/18/26 12:48:07 PM UTC | 0 ⭐ | 3511 👁️ | Never ⏰ | []
Lua |

2.7 KB

|

Source Code

|

0 👍

/

0 👎

-- from: https://stackoverflow.com/questions/9168058/how-to-dump-a-table-to-console
-- author: Alundaio
-- Prints a table
-- Modded for custom indents, default indent is 2 spaces, can be customized (minimum 1)
function print_table(node, indent)
  if not indent then indent = 2 end
  if indent < 1 then indent = 1 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 .. string.rep(' ',depth * indent) .. key .. " = "..tostring(v)
        elseif (type(v) == "table") then
          output_str = output_str .. string.rep(' ',depth * indent) .. key .. " = {\n"
          table.insert(stack,node)
          table.insert(stack,v)
          cache[node] = cur_index+1
          break
        else
          output_str = output_str .. string.rep(' ',depth * indent) .. key .. " = '"..tostring(v).."'"
        end
 
        if (cur_index == size) then
          output_str = output_str .. "\n" .. string.rep(' ',(depth-1) * indent) .. "}"
        else
          output_str = output_str .. ","
        end
      else
        -- close the table
        if (cur_index == size) then
          output_str = output_str .. "\n" .. string.rep(' ',(depth-1) * indent) .. "}"
        end
      end
 
      cur_index = cur_index + 1
    end
 
    if (size == 0) then
      output_str = output_str .. "\n" .. string.rep(' ',(depth-1) * indent) .. "}"
    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)
  return output_str
end

Comments