Strange behaviour of string.find()?

Hi,
I have a strange problem!

I have the following code:

local text="asdfiletxt"
local s="Hello Corona user"
print( string.find(text, "e", -2 )) 
print(string.find(s, "e", -2))

The first “print” display “nil”
The second display 16 (the position of “e” from the end)

Why the first one fail to find the “e”?

Because you are telling it to start from the second to last character in the string.

@XeduR

According to
Solar2D Documentation — API Reference | Libraries | string | find (coronalabs.com)

It should start from the end:

This is the example from the documentation:

print ( string.find ( "Hello Corona user" , "e" , -5 ) ) --> first "e" 5 characters from end: 16 16

that 3rd argument tells the function string.find where to start the search.
in your first example string.find starts searching from the letter “x” onward. Like XeduR said, you started the search from the second to last character in the string.

Heres some more info: lua-users wiki: String Library Tutorial

@proV I’m new to Lua, but I’m not new to programming and I don’t understand what “first “e” 5 characters from the end” means!

Anyway, is there a function to find a character from the end?

aaah, i see! no worries, its a really cool language. you’ll be an expert soon :slight_smile:

Well I think it means that it is the first “e” in the last 5 characters of the string “Hello Corona user”. The last five characters of that string are " usEr". It searches only these 5 characters. It ignores all the other characters in “Hello Corona”.

I don’t know if this is what you meant, but this function returns the position of a character from the back:

local function findCharFromBack(string, char)

   local foundPosition = 0
   local searchPosition = 1
   local searching = true

   while searching do

      local search = string.find(string, char, searchPosition)
      if search then
         foundPosition = search
         searchPosition = search + 1
         if searchPosition > #string then searching = false end
      else
          searching = false
      end
   end

   if foundPosition > 0 then
      return foundPosition
   else 
      return nil 
   end
end

Hope it helps :slightly_smiling_face: