I am fetching an array of data from SQL, and then concatenating them as strings for display. The function looks like this:
function FetchTopStats( Conn, iLimit )
local sToReturn = "\tS.No. \t UserName \t Score\n\t"
SQLQuery = assert( Conn:execute( string.format( [[SELECT username, totalcount FROM chatstat ORDER BY totalcount DESC LIMIT %d]], iLimit ) ) )
DataArray = SQLQuery:fetch ({}, "a")
i = 1
while DataArray do
sToReturn = sToReturn..tostring( i ).."\t"..DataArray.username.." \t "..DataArray.totalcount.."\n\t"
DataArray = SQLQuery:fetch ({}, "a")
i = i + 1
end
return sToReturn
end
This gives me an output like:
S.No. UserName Score
1 aim 6641
2 time 5021
3 Shepard 4977
and so on. I am thinking of using a string.format
function, to have a display as follows:
S.No. UserName Score
1 aim 6641
2 time 5021
3 Shepard 4977
But, I am totally out of ideas on how to have this. The only option coming to my mind is checking string length of username, and then applying \t
accordingly. That, I want to use at the very last.
Well, you need to either find out the maximum length of username thus making the algorithm 2-pass, or limit it to some arbitrary (but reasonable) size and unconditionally chop off the tails of too long strings. Once you have the column width, you can use left or right aligned format strings:
> print(string.format("|%-10d|%-20s|%10d|", 1, "Shepard", 9000))
|1 |Shepard | 9000|
Also, for large tables consider using table.concat
for building the final output: it's considerably faster than repeatedly appending strings (refer to the Chapter 11.6 of PIL for explanation).