简体   繁体   中英

How do I turn a string into an array in Lua?

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

Using this code I was able to separate each word but now I need to be able to access just the nth word. How could I print just the second word for example? could I convert it to an array somehow then use something similar to

print words[2]

Like this:

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

Apart from printing "is" it follows it by:

is
a
test
string

 print words[2] 

You can only omit the parentheses for string literals and table constructors, like:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM