sixhaunt tau
sixhaunt tau

Reputation: 9

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]

Upvotes: 0

Views: 3152

Answers (1)

Nick Gammon
Nick Gammon

Reputation: 1171

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

Upvotes: 1

Related Questions