2014-10-08 51 views
0
s = "this is a test string" 
words = {} 
for w in s:gmatch("%w+") do table.insert(words, w) end 

使用此代码我能够分开每个单词,但现在我需要能够访问只是第n个单词。例如,我怎么能打印第二个单词?可能我把它转换成数组莫名其妙然后使用类似的东西来如何在Lua中将字符串转换为数组?

print words[2] 
+0

你已经有答案了:'打印(字[2])'。 – 2014-10-08 17:11:54

+0

它不起作用(“input:4:'='期望靠近'words'”) – 2014-10-08 17:12:40

+0

编辑你用来完成的代码。 – 2014-10-08 17:13:42

回答

0

像这样:

s = "this is a test string" 
words = {} 
for w in s:gmatch("%w+") do 
    table.insert(words, w) 
end 

print (words [2]) --> is 

for k, v in ipairs (words) do 
    print (v) 
end -- for 

除了印刷 “是” 通过它遵循它:

is 
a 
test 
string 

print words[2] 

只能省略括号的字符串文字和表格的构造函数,如:

print "hello, world" 
print (table.getn { "the", "quick", "brown", "fox" }) --> 4 
+0

这不是真的,你只能省略字符串文字的parens,它也适用于表格构造函数。参见[BNF in the specs](http://www.lua.org/manual/5.3/manual.html#9):'args :: ='('[explist]')'| tableconstructor | LiteralString'。 – 2016-02-07 08:53:20

+0

哦,是的,你是对的。 **和**表构造函数。我会修改我的帖子。 – 2016-02-07 08:59:26

相关问题