将可变长度字符串连接为表 [英] Concatenate variable-length-strings as table
问题描述
我正在从SQL提取数据数组,然后将它们串联为显示字符串.该函数如下所示:
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
这给了我这样的输出:
S.No. UserName Score
1 aim 6641
2 time 5021
3 Shepard 4977
,依此类推.我正在考虑使用string.format
函数,使其显示如下:
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
但是,我完全不知道如何使用它.我想到的唯一选择是检查用户名的字符串长度,然后相应地应用\t
.那是我最后要用的.
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|
此外,对于大型表,请考虑使用table.concat
生成最终输出:这比重复追加字符串要快得多(请参阅 PIL第11.6章进行解释).
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).
这篇关于将可变长度字符串连接为表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!