Skip to content

Instantly share code, notes, and snippets.

@aniruddha-a
Created April 23, 2014 10:45
Show Gist options
  • Save aniruddha-a/11210453 to your computer and use it in GitHub Desktop.
Save aniruddha-a/11210453 to your computer and use it in GitHub Desktop.
PrettyTable - in Lua (just a test, not a full fledged module, or as powerful as the Py counterpart)
-- Tue Apr 22 15:46:42 IST 2014
-- Aniruddha. A
--
-- just to see how much effort it is to simulate Py like PrettyTable module
local function max(a,b) return a < b and b or a end
local function printf(...) return io.stdout:write(string.format(...)) end
function pad(s, width, padchar)
local padder = string.rep(padchar or ' ', width)
if width < 0 then return string.sub(padder .. s, width) end
return string.sub(s .. padder, 1, width)
end
function calign(s, width)
local spaces = width - #s
local x = math.floor(spaces/2)
return string.rep(' ',x) .. s .. string.rep(' ', width - x - #s)
end
function prettytable(t)
assert(t.heading, "Need a `heading' for the table!") -- mandatory table, which determines formatting
local ncols = #t.heading
t.width = {}
for i=1,ncols do
t.width[i] = #t.heading[i]
end
for j=1,#t do -- each data entry in the table
for i=1,ncols do -- as many cols as the heading
t.width[i] = max(t.width[i], #tostring(t[j][i]))
end
end
-- Print heading
printf('\n+')
for i=1,#t.width do
printf('-%s-+', pad('', t.width[i], '-'))
end
printf('\n|')
for i,h in ipairs(t.heading) do
printf(' %s |', calign(h, t.width[i])) -- only the header is center aligned
end
printf('\n+')
for i=1,#t.width do
printf('-%s-+', pad('', t.width[i], '-'))
end
-- Print the rows
for i=1,#t do
printf('\n|')
for j,v in ipairs(t[i]) do
printf(' %s |', pad(v, t.width[j]))
end
end
-- End
printf('\n+')
for i=1,#t.width do
printf('-%s-+', pad('', t.width[i], '-'))
end
printf('\n')
end
----------------- Test ------------------------
-- User input (TODO: add a neat API )
local tbl = { heading = { 'A', 'Hello', 'World' },
-- data --
{ 101, 222 , 123 },
{ 'an', 'a bad ass str', '1243c' }
}
prettytable(tbl)
-- TODO: handle the align/justify to left/center or right as a user option
-- TODO: provide an option to dump a slice of the column like select only one, or more columns
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment