suggest lua code to split string into words and put them into an array
- User
suggest lua code to split string into words and put them into an array
- Assistant
Here's an example of Lua code to split a string into words and insert them into an array:
function splitString(input_string) local result_array = {} for word in string.gmatch(input_string, "%S+") do table.insert(result_array, word) end return result_array end -- Example usage local input_string = "Hello world, how are you?" local words_array = splitString(input_string) -- Print the resulting array for i, word in ipairs(words_array) do print(i, word) endOutput:
1 Hello 2 world, 3 how 4 are 5 you?In this code, the
splitStringfunction uses thestring.gmatchfunction with the pattern"%S+"to iterate over each word in the input string. The%S+pattern matches one or more non-space characters, effectively splitting the string into words. Each word is then inserted into theresult_arrayusingtable.insert. Finally, the resulting array is returned for further use. - User
for old lua without gmatch
- Assistant
If you're working with an older version of Lua that doesn't support
string.gmatch, you can achieve the same result using thestring.matchandstring.findfunctions. Here's an example:function splitString(input_string) local result_array = {} local startPos = 1 local endPos = 1 while endPos do startPos, endPos = string.find(input_string, "%w+", endPos) if startPos and endPos then local word = string.sub(input_string, startPos, endPos) table.insert(result_array, word) endPos = endPos + 1 end end return result_array end -- Example usage local input_string = "Hello world, how are you?" local words_array = splitString(input_string) -- Print the resulting array for i, word in ipairs(words_array) do print(i, word) endOutput:
1 Hello 2 world 3 how 4 are 5 youIn this code, the
splitStringfunction uses a while loop along withstring.findto find the start and end positions of each word in the input string. The pattern matches one or more alphanumeric characters, effectively splitting the string into words. Each word is then extracted using and inserted into the . Finally, the resulting array is returned for further use.