Easy string.find question

Hello, problem:

xp = "abcdef"
ty = string.find(xp,"cde")

Now the first print shows two values. The second print shows just one value. For the exact same thing.


Why do they do something difference?

How do I access the SECOND value in string.find as a variable (like the second print)? I tried ty[2] and it didn’t work…

It seem to be printing the function of find, or the variables of it anyway, the 5 is end of cde so use string length of cde + ty-1 to get the 5 instead


the first print as shown gave me an error
so i recoded as

xp = "abcdef"

The first and second prints are giving you numbers that denote where in the string those characters are found if you were to do this instead

xp = "abcdef"
ty = string.find(xp,"cde")

I think the last one would give you what you’re after. Alternatively you could just use

ty = string.match(xp,"cde")

ty[2] would only work if ty was a table. What youre saying when you use ty[2] is that you want to reference the table ty’s 2nd index. Since ty isn’t a table you’d get nil.

.@david19801 string.find is returning two values. The print function prints them both, but you are only capturing the first result in your ty variable.

From the string.find documentation:

Looks for the first match of pattern in the string s. If it finds a match, then find returns the indices of s where this occurrence starts and ends; otherwise, it returns nil.

So it is returning the start index of “cde” and the end index of the match in the string “abcdef”.

If you want to capture both variables, do it like this:

start, last = string.find(xp, "cde")

print( start, last )

Edit: changed end → last

It returns a Boolean as well though if you have 4 args

.@Simeon what you’d get if you did that is error unexpected symbol near ‘end’

Yes! I just figured it out before seeing your guys’s answer! I used


Now ty is 3, and tz holds the 5. I remember seeing something similar with two variables = one thing in one of the examples.

Thanks for your help guys!

Now the question is, is it possible to get out just the second element alone? (just the tz in the example), without setting a ty first? like array[2] kinda…



so set just one variable, and make it equal to the second element? basically, how to access just the second element of string.find?

.@Sherrpen good point, that will teach me to use keywords as variable names :slight_smile:

.@Simeon still it is a good template for thinking of how to use variables in their place.

I can think of two ways, to get only the second returned element:

  1. assign a useless key and use only the second, logical one:

_, tz=string.find(xp,"cde")
  1. using from table:



.@se24vad tested and this is what you get

error: [string “-- t ex…”]:8: bad argument #1 to ‘find’ (string expected, got nil)

.@BridgetMoris you have to use @se24vad’s code in the context of the original poster, that is, xp needs to be a variable declared as follows:

xp = "abcdef"