[Coco] INSTR question

Allen Huffman alsplace at pobox.com
Thu Feb 9 16:12:15 EST 2017


I've been doing a series on Optimizing COLOR BASIC on my www.subethasoftware.com page lately, as well as a series on interfacing 6809 assembly with BASIC using the DEFUSR command. As such, I've been benchmarking all kinds of things in BASIC and finding many speed differences -- stuff I wish I had done in the 80s. Programs could generally be much faster with minor tweaks (which I am covering in my articles).

Here's a head scratcher that maybe someone can explain or confirm it's a bug:

INSTR(position, search-string, target)
* Position is optional.

INSTR returns a 0 if any of the following is true:
1. The position is greater than the number of characters in the search-string.
2. The search-string is null (contains no characters).
3. INSTR cannot find the target.

I use it for one key menus:

10 A$=INKEY$:IF A$="" THEN 10
20 LN=INSTR("ABCD", A$)
30 IF LN=0 THEN 10
40 ON LN GOTO 100,200,300,400
...etc...

PRINT INSTR("ABC", "A")
1

PRINT INSTR("ABC", "B")
2

PRINT INSTR("ABC", "C")
3

...as expected. Here are the 0 cases:

1. The position is greater than the number of characters in the search-string.
PRINT INSTR(5, "ABCD", "B")
0

2. The search-string is null (contains no characters).

PRINT INSTR("", "X")
0

3. INSTR cannot find the target.

PRINT INSTR("ABCD", "X")
0

...but I noticed today it finds the empty string: ""

PRINT INSTR("ABCDE", "")
1

That seems like a bug.
A$=""
PRINT INSTR("ABCD", A$)
1

I mention this because I found it was faster to parse on INKEY$ without using a variable:

ON INSTR("ABCD", INKEY$) GOTO 100,200,300,400

...but it returns 1 if there is nothing waiting, just as if it matched the first character of the search string :(

A lousy work-around is to use a dummy value in the first position of the search string:

10 ON INSTR("*ABC", INKEY$) GOSUB 100,200,300,400
20 GOTO 10
100 RETURN
200 PRINT "A PRESSED":RETURN
300 PRINT "B PRESSED":RETURN
400 PRINT "C PRESSED":RETURN

I never tried to use INKEY$ directly until today, and benchmarks showed it was much faster for this than assigning a variable.

Just something I found interesting.

		-- Allen




More information about the Coco mailing list