Difference between string.find and string.match?

From the documentation, testing myself, and what not. It seems that string.find and string.match are basically the same, all that’s different is the fourth parameter in string.find.

Unless there is other differences or something?

Oh yeah and that string.match returns the pattern if its found, however string.find returns the start and end indicies of the pattern

The first two differences you mentioned in the post are the only differences. That’s it. In fact internally, both string.find and string.match calls only the function str_find_aux with only the find argument being different.
I’m not sure why was string.match added in Lua 5.1 (from Lua 5.0) but this is a question for the Lua author and unfortunately you will not find them on the Roblox DevForum.

static int str_find_aux(lua_State* L, int find)
{
    size_t ls, lp;
    const char* s = luaL_checklstring(L, 1, &ls);
    const char* p = luaL_checklstring(L, 2, &lp);
    int init = posrelat(luaL_optinteger(L, 3, 1), ls);
    if (init < 1)
        init = 1;
    else if (init > (int)ls + 1)
    {                   // start after string's end?
        lua_pushnil(L); // cannot find anything
        return 1;
    }
    // explicit request or no special characters?
    if (find && (lua_toboolean(L, 4) || nospecials(p, lp)))
    {
        // do a plain search
        const char* s2 = lmemfind(s + init - 1, ls - init + 1, p, lp);
        if (s2)
        {
            lua_pushinteger(L, (int)(s2 - s + 1));
            lua_pushinteger(L, (int)(s2 - s + lp));
            return 2;
        }
    }
    else
    {
        MatchState ms;
        const char* s1 = s + init - 1;
        int anchor = (*p == '^');
        if (anchor)
        {
            p++;
            lp--; // skip anchor character
        }
        prepstate(&ms, L, s, ls, p, lp);
        do
        {
            const char* res;
            reprepstate(&ms);
            if ((res = match(&ms, s1, p)) != NULL)
            {
                if (find)
                {
                    lua_pushinteger(L, (int)(s1 - s + 1)); // start
                    lua_pushinteger(L, (int)(res - s));    // end
                    return push_captures(&ms, NULL, 0) + 2;
                }
                else
                    return push_captures(&ms, s1, res);
            }
        } while (s1++ < ms.src_end && !anchor);
    }
    lua_pushnil(L); // not found
    return 1;
}

static int str_find(lua_State* L)
{
    return str_find_aux(L, 1);
}

static int str_match(lua_State* L)
{
    return str_find_aux(L, 0);
}
1 Like

Alright thank you for your help.

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.