首页 > 解决方案 > Lua 打印在同一行

问题描述

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

我的意见是:@lua 很有趣

谢谢!

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

标签: lualua-table

解决方案


您的代码存在问题:

  • words表并未真正按原样使用。你只需要一个长度表而不是一个单词表,
  • “解析”逻辑不脱离“用户界面”,
  • 没有提示用户输入的消息,
  • 不需要的全局变量,
  • 也可以保证它n是一个数字io.read ('*number', '*line')
  • 字长可以使用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

推荐阅读