@SuppressWarnings({"PMD.NPathComplexity", "PMD.ExcessiveMethodLength"})
    private static int findAux (LuaCallFrame callFrame, boolean find ) {
        String f = find ? names[FIND] : names[MATCH];
        String source = (String) BaseLib.getArg(callFrame, 1, BaseLib.TYPE_STRING, f);
        String pattern = (String) BaseLib.getArg(callFrame, 2, BaseLib.TYPE_STRING, f);
        Double i = ((Double)(BaseLib.getOptArg(callFrame, 3, BaseLib.TYPE_NUMBER)));
        boolean plain = LuaState.boolEval(BaseLib.getOptArg(callFrame, 4, BaseLib.TYPE_BOOLEAN));
        int init = (i == null ? 0 : i.intValue() - 1);

        if ( init < 0 ) {
            // negative numbers count back from the end of the string.
            init += source.length();
            if ( init < 0 ) {
                init = 0; // if we are still negative, just start at the beginning.
            }
        } else if ( init > source.length() ) {
            init = source.length();
        }

        if ( find && ( plain || noSpecialChars(pattern) ) ) { // explicit plain request or no special characters?
            // do a plain search
            int pos = source.indexOf(pattern, init);
            if ( pos > -1 ) {
                return callFrame.push(LuaState.toDouble(pos + 1), LuaState.toDouble(pos + pattern.length()));
            }
        } else {
            StringPointer s = new StringPointer(source);
            StringPointer p = new StringPointer(pattern);

            MatchState ms = new MatchState ();
            boolean anchor = false;
            if ( p.getChar () == '^' ) {
                anchor = true;
                p.postIncrString ( 1 );
            }
            StringPointer s1 = s.getClone();
            s1.postIncrString ( init );

            ms.callFrame = callFrame;
            ms.src_init = s.getClone();
            ms.endIndex = s.getString().length();
            do {
                StringPointer res;
                ms.level = 0;
                if ( ( res = match ( ms, s1, p ) ) != null ) {
                    if ( find ) {
                        return callFrame.push(new Double(s.length () - s1.length () + 1), new Double(s.length () - res.length ())) +
                        pushCaptures( ms, null, null );
                    } else {
                        return pushCaptures( ms, s1, res );
                    }
                }

            } while ( s1.postIncrStringI ( 1 ) < ms.endIndex && !anchor );
        }
        return callFrame.pushNil();  // not found
    }
Only works with non-negative numbers
main/src/main/java/cgeo/geocaching/wherigo/kahlua/stdlib/StringLib.java