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:




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:






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
        startpos = #s - startpos + 1

    return startpos, endpos


^^^ 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
local str = ‘Test,test2,test3’
local num = 7

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

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 :wink:

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