Lua print in same line
2020-10-19 5:9:41
收藏:0
阅读:148
评论:2
这是我的代码。我想要输出如下内容 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
点赞
用户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
评论区的留言会收到邮件通知哦~
推荐文章
- Lua 虚拟机加密load(string.dump(function)) 后执行失败问题如何解决
- 我想创建一个 Nginx 规则,禁止访问
- 如何将两个不同的lua文件合成一个 东西有点长 大佬请耐心看完 我是小白研究几天了都没搞定
- 如何在roblox studio中1:1导入真实世界的地形?
- 求解,lua_resume的第二次调用继续执行协程问题。
- 【上海普陀区】内向猫网络招募【Skynet游戏框架Lua后端程序员】
- SF爱好求教:如何用lua实现游戏内调用数据库函数实现账号密码注册?
- Lua实现网站后台开发
- LUA错误显式返回,社区常见的规约是怎么样的
- lua5.3下载库失败
- 请问如何实现文本框内容和某个网页搜索框内容连接,并把网页输出来的结果反馈到另外一个文本框上
- lua lanes多线程使用
- 一个kv数据库
- openresty 有没有比较轻量的 docker 镜像
- 想问一下,有大佬用过luacurl吗
- 在Lua执行过程中使用Load函数出现问题
- 为什么 neovim 里没有显示一些特殊字符?
- Lua比较两个表的值(不考虑键的顺序)
- 有个lua简单的项目,外包,有意者加微信 liuheng600456详谈,最好在成都
- 如何在 Visual Studio 2022 中运行 Lua 代码?

以下是你代码存在的问题:
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