split string help
Posted: 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'.
the above code will only catch 'World' if str was 'Hello World' and store that in a, b is nil
I tried this but as expected it quits after the first iteration, so a is 'Hello' but b is nil
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.
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.
Then you can store that into a variable and index the table[1] and table[2] to get the first two entries.
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
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
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
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
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]