Comparison

util/human/io.lua @ 10893:a256044c1d12

util.human.io: table: switch row function to simply returning prepared row string
author Matthew Wild <mwild1@gmail.com>
date Wed, 03 Jun 2020 22:45:33 +0100
parent 10891:8d47858805c9
child 10894:d15a4284fdf8
comparison
equal deleted inserted replaced
10892:b9ff7178787c 10893:a256044c1d12
91 91
92 local function padleft(s, width) 92 local function padleft(s, width)
93 return string.rep(" ", width-#s)..s; 93 return string.rep(" ", width-#s)..s;
94 end 94 end
95 95
96 local function table(col_specs, max_width, padding) 96 local function new_table(col_specs, max_width, padding)
97 max_width = max_width or 80; 97 max_width = max_width or 80;
98 padding = padding or 4; 98 padding = padding or 4;
99 99
100 local widths = {}; 100 local widths = {};
101 local total_width = max_width - padding; 101 local total_width = max_width - padding;
116 local pc_width = tonumber((col_specs[i].width:gsub("%%$", ""))); 116 local pc_width = tonumber((col_specs[i].width:gsub("%%$", "")));
117 widths[i] = math.floor(free_width*(pc_width/100)); 117 widths[i] = math.floor(free_width*(pc_width/100));
118 end 118 end
119 end 119 end
120 120
121 return function (row, f) 121 return function (row)
122 local output = {};
122 for i, column in ipairs(col_specs) do 123 for i, column in ipairs(col_specs) do
123 local width = widths[i]; 124 local width = widths[i];
124 local v = tostring(row[column.key or i] or ""):sub(1, width); 125 local v = tostring(row[column.key or i] or ""):sub(1, width);
125 if #v < width then 126 if #v < width then
126 if column.align == "right" then 127 if column.align == "right" then
127 v = padleft(v, width-1).." "; 128 v = padleft(v, width-1).." ";
128 else 129 else
129 v = padright(v, width); 130 v = padright(v, width);
130 end 131 end
131 end 132 end
132 (f or io.stdout):write(v); 133 table.insert(output, v);
133 end 134 end
134 (f or io.stdout):write("\n"); 135 return table.concat(output);
135 end; 136 end;
136 end 137 end
137 138
138 return { 139 return {
139 getchar = getchar; 140 getchar = getchar;
143 read_password = read_password; 144 read_password = read_password;
144 show_prompt = show_prompt; 145 show_prompt = show_prompt;
145 printf = printf; 146 printf = printf;
146 padleft = padleft; 147 padleft = padleft;
147 padright = padright; 148 padright = padright;
148 table = table; 149 table = new_table;
149 }; 150 };