Jump to content

Recommended Posts

Posted

So I've run across a strange bug in my scripts that I can't, for the life of me, figure out and would like your kind help to save what reminds of my rapidly declining hairline.

Background: I want to check if an aircraft type is an A-10 -- A-10A, A-10C or A-10C_2. Since this is a common problem, my approach is to simply check if the type string begins with "A-10", since that is common to all types.

In code, this could look like this:

local theString = "A-10A"
local theMatch = "A-10"
local i, j = string.find(theString, theMatch)

What does the Lua Book say on this?

Quote

The basic use of string.find is to search for a pattern inside a given string, called the subject string. The function returns the position where it found the pattern or nil if it could not find it. The simplest form of a pattern is a word, which matches only a copy of itself. For instance, the pattern 'hello' will search for the substring "hello" inside the subject string. When find finds its pattern, it returns two values: the index where the match begins and the index where the match ends.

    s = "hello world"
    i, j = string.find(s, "hello")
    print(i, j)                      --> 1    5

Therefore, my expectation would be that i and j in my example (string.find("A-10A", "A-10")) would be 1 and 4

However...

image.png

I can't explain that. I suspect that "A-10A" and "A-10" are somehow seen as patterns, but I don't know why they should be nor as what pattern.

So, in a nutshell: why does my code return this strange result for string.find()?

Thank you for any pointers.

Lua find() oddity.miz

Posted
2 minutes ago, AdrianL said:

You need to escape the '-' in theMatch

Ouch. Thanks! So it is a pattern, and the "-" is interpreted as "0 or repetitions" of the "1" that follows. 

That's a tricky little snare to step in when looking for type strings with find...

Posted (edited)

Ha, seems there's a 'plaintext' search option for string.find() that I did not know about that solves this issue for me:

Quote

string.find (s, pattern [, init [, plain]])

A value of true as a fourth, optional argument plain turns off the pattern matching facilities, so the function does a plain "find substring" operation, with no characters in pattern being considered magic. Note that if plain is given, then init must be given as well.

so

local i, j = string.find(theString, theMatch, 1, true)

returns the correct result. 

Thank you so much @AdrianL for putting me on the right track! 

Edited by cfrag
  • cfrag changed the title to Need some basic Lua advice (string.find() oddity)
  • Recently Browsing   0 members

    • No registered users viewing this page.
×
×
  • Create New...