将变长字符串连接起来作为表格。

我正在从 SQL 中获取一个数组的数据,然后将它们作为字符串拼接显示。该函数如下:

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 函数将显示格式如下:

    S.No.    UserName    Score
    1       aim          6641
    2       time         5021
    3       Shepard      4977

但是,我完全没有头绪。我脑海中浮现的唯一选项是检查用户名的字符串长度,然后相应地应用 \t。我想在最后使用它。

原文链接 https://stackoverflow.com/questions/10089527

点赞
stackoverflow用户200540
stackoverflow用户200540

好的,你需要找出用户名的最大长度,从而使算法进行两次通行,或者将其限制为某个任意(但合理)的大小并无条件地将太长的字符串尾巴砍掉。一旦你有了列宽,你就可以使用左对齐或右对齐的格式字符串:

> print(string.format("|%-10d|%-20s|%10d|", 1, "Shepard", 9000))
|1         |Shepard             |      9000|

另外,对于大表,考虑使用table.concat来构建最终输出:它比重复添加字符串快得多(参见PIL第11.6章的解释)。

2012-04-10 13:34:56