Page 1 of 1

split string help

Posted: Thu Jul 26, 2018 1:58 pm
by Ekamu
I want to get a string such as 'Hello World' and store the first two words in variables 'a' and 'b'.

Code: Select all

function word(str,a,b) --assume str is 'Hello World'
	for i,j in str:gmatch("%w+") do 
			a,b = i,j --catches I twice the second time its nil
	end
	return a,b
end
the above code will only catch 'World' if str was 'Hello World' and store that in a, b is nil

Code: Select all

function word(str) --assume str is 'Hello World'
	for i,j in str:gmatch("%w+") do 
			return i,j --only catches I and quits
	end
end
I tried this but as expected it quits after the first iteration, so a is 'Hello' but b is nil

Code: Select all

function word(str) --assume str is 'Hello World'
	for i,j in str:gmatch("%w+") do 
	 print(i,j) --catches both I and j and prints
	end
end
this works, it prints 'Hello' and then 'World' but how do I get those values and store them into variables.

SOLVED:
I found a solution.

Code: Select all

function split(s, delimiter)
    result = {}
    for match in (s..delimiter):gmatch("(.-)"..delimiter) do
        table.insert(result, match)
    end
    return result
end
split a string in Lua


so the above code splits a string based on the delimiter for example " " (space) and stores that in a table result and returns that table.

Code: Select all

local splice = split(text," ")
input1,input2 = splice[1],splice[2]
Then you can store that into a variable and index the table[1] and table[2] to get the first two entries.

Re: split string help

Posted: Thu Jul 26, 2018 2:18 pm
by pgimeno
For separating into an undefined number of words, I'd suggest using a table. But since in your case you only want two words, it's simpler to do it this way:

Code: Select all

  local a, b = string.match(str, "(%w+)%W+(%w+)")
If the input may also contain just one word, add this line after the above one:

Code: Select all

if not a then a = string.match(str, "%w+") end