Advertisement
enimaloc

print_utils.lua

Jul 13th, 2025
288
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Lua 2.23 KB | None | 0 0
  1. -- print_utils.lua
  2.  
  3. local print_utils = {}
  4.  
  5. local level_colors = {
  6.     info  = colors.white,
  7.     warn  = colors.yellow,
  8.     error = colors.red,
  9.     debug = colors.gray
  10. }
  11.  
  12. local function timestamp()
  13.     local t = textutils.formatTime(os.time(), true)
  14.     return "[" .. t .. "]"
  15. end
  16.  
  17. local function raw_tostring(val)
  18.     if type(val) == "string" then
  19.         return '"' .. val .. '"'
  20.     elseif type(val) == "boolean" then
  21.         return val and "true" or "false"
  22.     else
  23.         return tostring(val)
  24.     end
  25. end
  26.  
  27. -- Affiche une structure complète (table) avec indentation
  28. local function dump_table(tbl, indent, visited)
  29.     indent = indent or 0
  30.     visited = visited or {}
  31.  
  32.     if visited[tbl] then
  33.         return string.rep(" ", indent) .. "<circular reference>"
  34.     end
  35.     visited[tbl] = true
  36.  
  37.     local lines = {}
  38.     table.insert(lines, string.rep(" ", indent) .. "{")
  39.     for k, v in pairs(tbl) do
  40.         local keyStr = "[" .. raw_tostring(k) .. "]"
  41.         if type(v) == "table" then
  42.             table.insert(lines, string.rep(" ", indent + 2) .. keyStr .. " = " .. dump_table(v, indent + 2, visited))
  43.         else
  44.             local valStr = raw_tostring(v)
  45.             table.insert(lines, string.rep(" ", indent + 2) .. keyStr .. " = " .. valStr)
  46.         end
  47.     end
  48.     table.insert(lines, string.rep(" ", indent) .. "}")
  49.     return table.concat(lines, "\n")
  50. end
  51.  
  52. function print_utils.dump(obj)
  53.     if type(obj) == "table" then
  54.         return dump_table(obj)
  55.     else
  56.         return raw_tostring(obj)
  57.     end
  58. end
  59.  
  60. function print_utils.print_msg(level, msg)
  61.     if term.isColor then
  62.         term.setTextColor(level_colors[level] or colors.white)
  63.     end
  64.     print(timestamp() .. " [" .. level:upper() .. "] " .. msg)
  65.     if term.isColor then
  66.         term.setTextColor(colors.white)
  67.     end
  68. end
  69.  
  70. function print_utils.info(msg)
  71.     print_utils.print_msg("info", print_utils.dump(msg))
  72. end
  73.  
  74. function print_utils.warn(msg)
  75.     print_utils.print_msg("warn", print_utils.dump(msg))
  76. end
  77.  
  78. function print_utils.error(msg)
  79.     print_utils.print_msg("error", print_utils.dump(msg))
  80. end
  81.  
  82. function print_utils.debug(msg)
  83.     print_utils.print_msg("debug", print_utils.dump(msg))
  84. end
  85.  
  86. return print_utils
  87.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement