如何在Lua中将一个字符串转换为数组?

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

使用这段代码,我可以分离出每个单词,但现在我需要能够访问第n个单词。例如,我怎么能只打印第二个单词?我能把它转换成一个数组,然后使用类似以下的东西吗?

print words[2]
点赞
用户5043289
用户5043289
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”之外,它还打印:

is
a
test
string

print(words[2])

您只能省略字符串字面值和表构造函数的括号,例如:

print "hello, world"
print (table.getn { "the", "quick", "brown", "fox" }) --> 4
2016-02-07 07:19:15