Reputation: 3236
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.
Upvotes: 5
Views: 6217
Reputation: 48619
This will also work:
result = mystring:sub((mystring:find(';')))
The extra parentheses ensure that sub
is called with only one argument, so it will use the default (the end of mystring
) for the second argument.
Upvotes: 1
Reputation: 72312
Try this:
s="first part;second part"
print(s:match(";(.-)$"))
or this:
print(s:sub(s:find(";")+1,-1))
Upvotes: 3
Reputation: 4340
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 ';'.
Upvotes: 3