2016-02-13 79 views
1

我想制作一个脚本,它可以接受任意数字,向上计数并以格式返回它们。 所以这样在lua中以格式化字符串

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 

,我希望它甚至有事情超过900个所以像工作20会是这样的

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

我相信它可以使用lua中的字符串库来完成,但我不知道如何使用该库。

任何帮助?

回答

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) 
+0

或者将io.write()和if ...结合起来:io.write(i,i%per_line == 0和'\ n'或'\ t') – tonypdmtr

2

for拿到可选的第三

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

谢谢!这正是我需要的。 – Alexwall

0

我能想到的2种方法来做到这一点:

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 
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