There is a solution that involves a for loop checking every letter. It'd add a letter to a buffer if it wasn't a space, and would flush the buffer (would insert its content into a table and empty it) if it was a space. That's the more tedious one, and I won't be explaining that.
Here's one with
string.gmatch (
read about it here):
local words = {}
for word in str:gmatch("%S+") do
table.insert(words, word)
end
The above code splits
str into words
not containing anything that matches the character class
"%s" (remeber,
not containing, hence the
"%S" with the uppercase S), which would be space, newline, tabs and form feed, if I recall correctly. It also ignores empty matches, so splitting
"a b" -- note the double space
would result in
{"a", "b"}
, not in
{"a", "", "b"}
.
You could use
"[^ ]+" instead of
"%S" to allow anything
but space in the resulting words, or also anything else, for example
"[^;]+" would split
str along semicolons.
Since you're planning to parse command lines with this, I must add that this solution is a bit complicated to extend to allow commands with quotes or backslashes to escape spaces, such as
program arg1 arg2 "this is arg3"
program arg1 arg2 this\ is\ arg3
Edited by LBPHacker, 03 July 2016 - 10:29 AM.