lua-users home
lua-l archive

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]


On Fri, Jun 16, 2017 at 3:37 PM John Gabriele <jgabriele@fastmail.fm> wrote:
Hi lua-l,

I understand that:

    > s = 'hello there hi'
    > -- this
    > s:find('there')
    7       11
    > -- is the same as
    > s.find(s, 'there')
    7       11

but what exactly is going on with:

    > -- this
    > s.find(s, 'there')
    7       11
    > -- vs
    > string.find(s, 'there')
    7       11

?

Thanks,
-- John

Since Lua 5.1, strings have a metatable with an __index field referencing the `string` table. Since strings cannot be directly indexed, any attempt to index a string (e.g. `s.find(s, 'there')`) falls back to the __index metamethod, which tells Lua to repeat the indexing in the `string` table. The last example (`string.find(s, 'there')`) simply bypasses that metatable completely and indexes the `string` table directly. Either way, it's the same function: `s.find == string.find`.