Search code examples
stringluasplitlua-patterns

How to take out only 1 word from a string in Lua


I know how to split the whole string and put it in a table but I need to take out only the first word and then the rest of the string needs to stay the same.

I tried to do something on this but I have no idea:

words = {}
for word in s:gmatch("%w+") do table.insert(words,word) end

Solution

  • To match one word, you should use string.match instead of string.gmatch:

    local words = {}
    words[1], words[2] = s:match("(%w+)(.+)")
    

    words[1] contains the first word, the words[2] contains the rest.