在模式中以lua格式化字符串

时间:2016-02-13 04:49:09

标签: lua formatting

我想创建一个脚本,它接受任何数字,计算它们并以格式返回它们。 所以喜欢这个

for i = 1,9 do
print(i)
end

将返回

1
2
3
4
5
6
7
8
9

然而我希望它像这样打印

1 2 3
4 5 6
7 8 9

我希望它能在超过9的情况下工作,所以像20这样的东西就像这样

1 2 3
4 5 6
7 8 9
10 11 12
13 14 15
16 17 18
19 20

我确定可以使用lua中的字符串库来完成,但我不确定如何使用该库。

任何帮助?

4 个答案:

答案 0 :(得分:2)

for循环采用可选的第三个步骤

for i = 1, 9, 3 do
  print(string.format("%d %d %d", i, i + 1, i + 2))
end

答案 1 :(得分:2)

function f(n,per_line)
  per_line = per_line or 3
  for i = 1,n do
    io.write(i,'\t')
    if i % per_line == 0 then io.write('\n') end
  end
end

f(9)
f(20)

答案 2 :(得分:0)

我可以想到两种方法:

local NUMBER = 20
local str = {}
for i=1,NUMBER-3,3 do
    table.insert(str,i.." "..i+1 .." "..i+2)
end
local left = {}
for i=NUMBER-NUMBER%3+1,NUMBER do
    table.insert(left,i)
end
str = table.concat(str,"\n").."\n"..table.concat(left," ")

另一个使用gsub:

local NUMBER = 20
local str = {}
for i=1,NUMBER do
    str[i] = i
end
-- Makes "1 2 3 4 ..."
str = table.concat(str," ")
-- Divides it per 3 numbers
-- "%d+ %d+ %d+" matches 3 numbers divided by spaces
-- (You can replace the spaces (including in concat) with "\t")
-- The (...) capture allows us to get those numbers as %1
-- The "%s?" at the end is to remove any trailing whitespace
-- (Else each line would be "N N N " instead of "N N N")
-- (Using the '?' as the last triplet might not have a space)
--    ^ e.g. NUMBER = 6 would make it end with "4 5 6"
-- The "%1\n" just gets us our numbers back and adds a newline
str = str:gsub("(%d+ %d+ %d+)%s?","%1\n")
print(str)

我已经对两个代码段进行了基准测试。上面的一点点快一点,虽然差别几乎没有:

Benchmarked using 10000 interations
NUMBER   20        20        20        100       100
Upper    256 ms    276 ms    260 ms    1129 ms   1114 ms
Lower    284 ms    280 ms    282 ms    1266 ms   1228 ms

答案 3 :(得分:0)

使用临时表来包含值,直到您打印它们为止:

local temp = {}
local cols = 3

for i = 1,9 do
    if #temp == cols then
       print(table.unpack(temp))
        temp = {}
    end
    temp[#temp + 1] = i
end

--Last minute check for leftovers
if #temp > 0 then
    print(table.unpack(temp))
end
temp = nil
相关问题