Display Table Function

Share your scripts and packages with other Mudlet users.
Post Reply
Jor'Mox
Posts: 1142
Joined: Wed Apr 03, 2013 2:19 am

Display Table Function

Post by Jor'Mox »

Here is a somewhat fixed up function I made to display tables fancily. It draws out "cells" in which the table values are displayed, has the option to have a "title" for the table, with a configurable number of columns, column width, and colors for data values, title, and "frame". If no width is given, it defaults to just big enough to show the largest data value.

If a keyed table is used, both keys and values are displayed, with keys adjacent to their values. If the data table contains a table, that item will be shown with the values concatenated together, surrounded by curly brackets. There are some obvious restrictions on what this will actually display, but it will definitely handle a fairly wide range of normal tables.
Code: [show] | [select all] lua
function display_table(data, columns, width, title, data_color, frame_color, title_color)
  data_color, frame_color, title_color = data_color or "green", frame_color or "white", title_color or "green"
  columns = columns or 4
  if type(data) ~= "table" then error("data argument must be a table of values to display",2) end
  local data_copy = table.deepcopy(data)
  if #data ~= table.size(data) then
    data_copy = {}
    for k, v in pairs(data) do
      table.insert(data_copy,k)
      table.insert(data_copy,v)
    end
  end
  for i, v in pairs(data_copy) do
    if type(v) == "table" then
      data_copy[i] = "{"..table.concat(v,",").."}"
    end
  end
  if not width then
    for _, v in ipairs(data_copy) do
      v = tostring(v)
      if not width or #v > width then
        width = #v
      end
    end
    width = width + 1
  end
  local row_width = (width+2) * columns + 1
  local spacer = string.format("<%s>%s<reset>\n", frame_color, string.rep("-", row_width))
  local item = "<".. frame_color ..">| <"..data_color..">%-"..width.."s"
  local no_item = string.format("<%s>| %s",frame_color, string.rep(" ", width))
  local end_line = string.format("<%s>|<reset>\n",frame_color)
  if title then cecho(string.format("<%s>%s\n",title_color,title)) end
  cecho(spacer)
  for i = 1,#data_copy,columns do
    for j = 0, columns - 1 do
      if data_copy[i+j] then
        cecho(string.format(item,data_copy[i+j]))
      else
        cecho(no_item)
      end
    end 
    cecho(end_line)
    cecho(spacer)
  end
end

Post Reply