Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

split a string on a separator

Tags:

lua

I have a string like first part;second part. I want to split it on the ; and return the second part. Everything works fine with:

start = mystring:find(';')
result = mystring:sub(start)

But I was hoping to do it on one line:

result = mystring:sub(mystring:find(';'))

It doesn't throws an error but it is not returning the expected result. Not a big issue as it works fine on two lines of code but understanding why it's not working on the oneliner will help me to better understand how lua works.

like image 737
ripat Avatar asked May 17 '11 16:05

ripat


2 Answers

find actually returns two values, which are the start and end indices of where the string you looked for is. In this case, both indices are 11.
When you then pass these two indices to sub, you get a substring that both starts and ends at 11, so you only get ';'.

like image 73
Zecc Avatar answered Oct 02 '22 17:10

Zecc


Try this:

s="first part;second part"  
print(s:match(";(.-)$"))

or this:

print(s:sub(s:find(";")+1,-1))
like image 44
lhf Avatar answered Oct 02 '22 19:10

lhf