Lua print in same line

这是我的代码。我想要输出如下内容 3,2,3 即用逗号分隔的值在同一行中,而不是在新行中获取值

我的输入是:@lua is fun

谢谢!

function countChar(s)
   words = {}
   for word in s:gmatch("%w+")
   do
       table.insert(words, word)
       print(#word)
   end
end
n = tonumber(io.read())
for i=1,n
do
    s=io.read();
    countChar(s)
end
点赞
用户6632736
用户6632736

以下是你代码存在的问题:

  • words 表并没有真正被使用。你只需要一个长度表,而不是一个单词表。
  • “解析”逻辑没有与“用户界面”分离。
  • 没有提示用户输入的消息。
  • 不必要的全局变量。
  • 可以使用 io.read('*number', '*line') 来确保 n 是一个数字。
  • 单词长度可以在一个表上使用 table.concat 打印在一行上。

这是我解决这些问题的建议:

local function countChar(s)
    local lengths = {}
    for word in s:gmatch '%w+' do
        table.insert(lengths, word:len())
    end
    return lengths
end

io.write 'Number of sentences: '
local n = io.read('*number', '*line')

for i = 1, n do
    io.write ('Sentence no. ' .. tostring(i) .. ': ')
    local s = io.read()
    io.write ('Word lengths: ' .. table.concat(countChar(s), ', ') .. '\n')
end

另外,没有必要提示用户句子的数量。可以一个一个读取句子,直到用户只按 Enter,也就是输入了一个空字符串。这个解决方案使用一个简单的迭代器来消耗用户输入并打印提示:

local function countChar(s)
    local lengths = {}
    for word in s:gmatch '%w+' do
        table.insert(lengths, word:len())
    end
    return lengths
end

local function getSentences()
    io.write ('Enter a sentence or just press Enter to finish: ')
    local input = io.read()
    if input == '' then
        input = nil -- this nil will stop the generic for loop below.
    end
    return input
end

for s in getSentences do
    io.write ('Word lengths: ' .. table.concat(countChar(s), ', ') .. '\n')
end
2020-10-19 05:45:37
用户3342050
用户3342050
#! /usr/bin/env lua

local function countChar(str)
    local numbers = ''
    for word in str:gmatch('%w+') do
        numbers = numbers .. #word .. ',' --  concatenate
    end
    return numbers:sub(1, -2) --  remove trailing comma
end

io.write('Phrase to count? ') --  @lua is fun
local phrase = io.read()
print(countChar(phrase))

输入要统计的短句:@lua is fun

输出:3,2,3

2020-10-21 05:54:43