Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/.htaccess/6.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在Lua中拆分字符串_Lua - Fatal编程技术网

在Lua中拆分字符串

在Lua中拆分字符串,lua,Lua,我对Lua很陌生,如果我听起来很蠢,我很抱歉。 我正在尝试制作一个程序,它有点像这样: 用户输入:“你好,世界” 你好 Var2:世界 因为我不知道我在做什么,所以我只知道test=io.read(),我不知道接下来要做什么 谢谢你的帮助 谢谢你,摩根。如果你想拆分单词,你可以这样做: input = "Hello world" -- declare a table to store the results -- use tables instead of single variables,

我对Lua很陌生,如果我听起来很蠢,我很抱歉。 我正在尝试制作一个程序,它有点像这样:

用户输入:“你好,世界” 你好 Var2:世界

因为我不知道我在做什么,所以我只知道test=io.read(),我不知道接下来要做什么

谢谢你的帮助


谢谢你,摩根。

如果你想拆分单词,你可以这样做:

input = "Hello world"

-- declare a table to store the results
-- use tables instead of single variables, if you don't know how many results you'll have
t_result = {}

-- scan the input
for k in input:gmatch('(%w+)') do table.insert(t_result, k) end
-- input:gmatch('(%w+)')
-- with generic match function will the input scanned for matches by the given pattern
-- it's the same like: string.gmatch(input, '(%w+)')
-- meaning of the search pattern:
---- "%w" = word character
---- "+"  = one or more times
---- "()" = capture the match and return it to the searching variable "k"

-- table.insert(t_result, k)
-- each captured occurence of search result will stored in the result table

-- output
for i=1, #t_result do print(t_result[i]) end
-- #t_result: with "#" you get the length of the table (it's not usable for each kind of tables)
-- other way:
-- for k in pairs(t_result) do print(t_result[k]) end
输出:

Hello
world

非常感谢您的回答!但我真的不明白这意味着什么。如果不太麻烦的话,你介意把代码的每一部分都分解成什么,以及如何将输出转换成变量吗?我真的很感谢你的回复。我现在添加了评论。如果结果计数未知,将结果存储在单个变量中是不明智的。当用户输入时,您不知道将输入多少单词。例如: