Software /
code /
prosody
Comparison
util/human/io.lua @ 10891:8d47858805c9
util.human.io: Add padleft, padright and a table printing function
author | Matthew Wild <mwild1@gmail.com> |
---|---|
date | Wed, 03 Jun 2020 22:21:17 +0100 |
parent | 10872:a3f3f42736f2 |
child | 10893:a256044c1d12 |
comparison
equal
deleted
inserted
replaced
10890:a451f80d1cea | 10891:8d47858805c9 |
---|---|
83 | 83 |
84 local function printf(fmt, ...) | 84 local function printf(fmt, ...) |
85 print(fmt:format(...)); | 85 print(fmt:format(...)); |
86 end | 86 end |
87 | 87 |
88 local function padright(s, width) | |
89 return s..string.rep(" ", width-#s); | |
90 end | |
91 | |
92 local function padleft(s, width) | |
93 return string.rep(" ", width-#s)..s; | |
94 end | |
95 | |
96 local function table(col_specs, max_width, padding) | |
97 max_width = max_width or 80; | |
98 padding = padding or 4; | |
99 | |
100 local widths = {}; | |
101 local total_width = max_width - padding; | |
102 local free_width = total_width; | |
103 -- Calculate width of fixed-size columns | |
104 for i = 1, #col_specs do | |
105 local width = col_specs[i].width or "0"; | |
106 if not(type(width) == "string" and width:sub(-1) == "%") then | |
107 local title = col_specs[i].title; | |
108 width = math.max(tonumber(width), title and (#title+1) or 0); | |
109 widths[i] = width; | |
110 free_width = free_width - width; | |
111 end | |
112 end | |
113 -- Calculate width of %-based columns | |
114 for i = 1, #col_specs do | |
115 if not widths[i] then | |
116 local pc_width = tonumber((col_specs[i].width:gsub("%%$", ""))); | |
117 widths[i] = math.floor(free_width*(pc_width/100)); | |
118 end | |
119 end | |
120 | |
121 return function (row, f) | |
122 for i, column in ipairs(col_specs) do | |
123 local width = widths[i]; | |
124 local v = tostring(row[column.key or i] or ""):sub(1, width); | |
125 if #v < width then | |
126 if column.align == "right" then | |
127 v = padleft(v, width-1).." "; | |
128 else | |
129 v = padright(v, width); | |
130 end | |
131 end | |
132 (f or io.stdout):write(v); | |
133 end | |
134 (f or io.stdout):write("\n"); | |
135 end; | |
136 end | |
137 | |
88 return { | 138 return { |
89 getchar = getchar; | 139 getchar = getchar; |
90 getline = getline; | 140 getline = getline; |
91 getpass = getpass; | 141 getpass = getpass; |
92 show_yesno = show_yesno; | 142 show_yesno = show_yesno; |
93 read_password = read_password; | 143 read_password = read_password; |
94 show_prompt = show_prompt; | 144 show_prompt = show_prompt; |
95 printf = printf; | 145 printf = printf; |
146 padleft = padleft; | |
147 padright = padright; | |
148 table = table; | |
96 }; | 149 }; |