Main Content

Dynamically formatting your results (Lua)

Archive - Originally posted on "The Horse's Mouth" - 2009-11-10 07:40:24 - Graham Ellis

Scenario: You're producing a short (text) table of results and you want to keep it reasonably small - not a great deal of white space, but the data in some of your columns differs dramatically from one set of results to another. How can you do it?

Discussion: You can use your traditional "printf" type formatting in C, Perl, PHP, Python (via the % operator), Lua (string.format) and Tcl (string format) to give each field a width, but you'll need to ensure that the fields are wide enough to take the data to be placed in them every time, or accept occasional spillages when the data "busts its bank".

Solution: Parse the data for the report before you print anything out at all, and calculate the maximum width for each field for the current report. Then make up your own dynamic formatting string for use just on this occaasion. Here's an example of what I mean:

oak = {"beer","beer","beer","beer","beer","legs",
  "spilled spaghetti sauce","top","draw",
  "spit","polish","secret"}
table.sort(oak)
 
-- ====================================
 
syze = #oak[1]
for k=2,#oak do
  if syze < #oak[k] then syze = #oak[k] end
end
 
clen = #(string.format("%d",#oak));
using = "%"..clen.."d %"..syze.."s"
print ("Output format: " .. using)
 
for k,v in ipairs(oak) do
  print (string.format(using,k,v))
  end
-- ====================================


And the result:

Output format: %2d %23s
1 beer
2 beer
3 beer
4 beer
5 beer
6 draw
7 legs
8 polish
9 secret
10 spilled spaghetti sauce
11 spit
12 top


Notes: 1. If the question had been asked for web use, I would have used a browser and a table in my html to do the dynamic formatting

2. The code in the ========== section should be saved as a function for re-use later