split string help

Questions about the LÖVE API, installing LÖVE and other support related questions go here.
Forum rules
Before you make a thread asking for help, read this.
Post Reply
Ekamu
Party member
Posts: 171
Joined: Fri Sep 20, 2013 11:06 am

split string help

Post by Ekamu » Thu Jul 26, 2018 1:58 pm

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.

User avatar
pgimeno
Party member
Posts: 1943
Joined: Sun Oct 18, 2015 2:58 pm
Location: Valencia, ES

Re: split string help

Post by pgimeno » Thu Jul 26, 2018 2:18 pm

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

Post Reply

Who is online

Users browsing this forum: steVeRoll and 5 guests