# Finding a string position according to another position

Confusing title.

What I mean is, say I had something like this:

``````

local str = 'Test,test2,test3'

``````

and I also had a number,

``````

local num = 7

``````

If I wanted to find the 7th character in that string, I (think) I’d get:

'Test,t

``````
e

``````

st2,test3’

Because ‘e’ is the 7th character.

But what I want to do, is get the position of the commas closest to either side of that character, so I’d like to get something like

``````

4        9

``````

The commas below are what I want to return the position of:

'Test

``````
,

``````

test2

``````
,

``````

test3’

How would I do this, since there isn’t a way to use string.find in reverse?

Also, if there are no commas at all (either on the left or right) then I’d need to just get the position of the start and/or end of the string instead.

``````
Edit: 29th October 2015

``````

I decided to try making a function to do this, but it’s probably very buggy:

``````

function string.GetCommasBetween( s, pos )

local endpos = string.find( s, ',', pos )
if endpos == nil then endpos = #s end
s = string.reverse(s)
local startpos = string.find( s, ',', #s - pos )
if startpos == nil then startpos = 0
else
startpos = #s - startpos + 1
end

return startpos, endpos

end

^^^ That function might give you an idea of what I want to do if you couldn't be bothered reading this post or it was too confusing

``````

Something like
[lua]
local str = ‘Test,test2,test3’
local num = 7

if num > #str or num < 1 then
print(“Out of range”)
else
local lB = 0
local uB = #str
for i=num, 1, -1 do
if string.sub(str, i, i) == “,” then
lB = i
break
end
end
for i=num, #str, 1 do
if string.sub(str, i, i) == “,” then
uB = i
break
end
end
print(lB … " " … uB)
end
[/lua]

Thanks for the example, but it’s still a bit longer than my original function, but good idea!

Sorry if I’m acting like an idiot but I’d like the function to be as short as possible so I can feel dumb.

Yeah, but your function doesn’t work properly

I thought something was wrong with it. I think I’ll use yours, thanks!