cfrag Posted January 26, 2023 Posted January 26, 2023 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... 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
AdrianL Posted January 26, 2023 Posted January 26, 2023 (edited) 12 minutes ago, cfrag said: why does my code return this strange result for string.find()? You need to escape the '-' in theMatch i.e. local theMatch = "A%-10" See https://www.lua.org/pil/20.2.html Edited January 26, 2023 by AdrianL 1
cfrag Posted January 26, 2023 Author Posted January 26, 2023 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...
cfrag Posted January 26, 2023 Author Posted January 26, 2023 (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 January 26, 2023 by cfrag
Recommended Posts