How would I get the position of a gsub iteration?

Example:

local d = "abc cba bca hhhhhhh"
string.gsub(d, "cba", function(a)
    -- how do i get the position of "cba"?
end)

So, 2 letters after cba would be ‘b’, I would like to get ‘b’, but how would I know where the “cba” is in the first place?

There’s the () pattern which captures the position of the string.

local d = "abc cba bca hhhhhhh"
string.gsub(d, "()cba", function(a)
        print(a) -- 5
end)

…or you can just use "c(b)a" as the pattern if you just need the b part of it.

2 Likes

That’s interesting. I had no idea you could do that with empty parentheses. I think position should be a function parameter anyways, but what do I know about making programming languages?

1 Like