|
| 1 | +-- Very simple pretty-printer of tabular data. |
| 2 | +-- |
| 3 | +-- Example: |
| 4 | +-- |
| 5 | +-- tabulate.encode({ |
| 6 | +-- {'a', 'b', 'c'}, |
| 7 | +-- tabulate.SPACER, |
| 8 | +-- {'d', 'e', 'f'}, |
| 9 | +-- {'g', 'h', 'i'}, |
| 10 | +-- }) |
| 11 | +-- |
| 12 | +-- -> |
| 13 | +-- |
| 14 | +-- | a | b | c | |
| 15 | +-- | - | - | - | |
| 16 | +-- | d | e | f | |
| 17 | +-- | g | h | i | |
| 18 | + |
| 19 | +local SPACER = {} |
| 20 | + |
| 21 | +-- Format data as a table. |
| 22 | +-- |
| 23 | +-- Accepts an array of rows. Each row in an array of values. Each |
| 24 | +-- value is a string. |
| 25 | +local function encode(rows) |
| 26 | + -- Calculate column widths and columns amount. |
| 27 | + local column_widths = {} |
| 28 | + for _i, row in ipairs(rows) do |
| 29 | + for j, v in ipairs(row) do |
| 30 | + assert(type(v) == 'string') |
| 31 | + column_widths[j] = math.max(column_widths[j] or 0, #v) |
| 32 | + end |
| 33 | + end |
| 34 | + local column_count = #column_widths |
| 35 | + |
| 36 | + -- Use a table as a string buffer. |
| 37 | + local acc = {} |
| 38 | + |
| 39 | + -- Add all the values into the accumulator with proper spacing |
| 40 | + -- around and appropriate separators. |
| 41 | + for _i, row in ipairs(rows) do |
| 42 | + if row == SPACER then |
| 43 | + for j = 1, column_count do |
| 44 | + local width = column_widths[j] |
| 45 | + table.insert(acc, '| ') |
| 46 | + table.insert(acc, ('-'):rep(width)) |
| 47 | + table.insert(acc, ' ') |
| 48 | + end |
| 49 | + table.insert(acc, '|\n') |
| 50 | + else |
| 51 | + for j = 1, column_count do |
| 52 | + assert(row[j] ~= nil) |
| 53 | + local width = column_widths[j] |
| 54 | + table.insert(acc, '| ') |
| 55 | + table.insert(acc, row[j]:ljust(width)) |
| 56 | + table.insert(acc, ' ') |
| 57 | + end |
| 58 | + table.insert(acc, '|\n') |
| 59 | + end |
| 60 | + end |
| 61 | + |
| 62 | + return table.concat(acc) |
| 63 | +end |
| 64 | + |
| 65 | +return { |
| 66 | + SPACER = SPACER, |
| 67 | + encode = encode, |
| 68 | +} |
0 commit comments