lua-users home
lua-l archive

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


On Fri, Jun 16, 2017, at 05:19 PM, Jonathan Goble wrote:
On Fri, Jun 16, 2017 at 5:02 PM John Gabriele <jgabriele@fastmail.fm> wrote:
On Fri, Jun 16, 2017, at 04:05 PM, Jonathan Goble wrote:
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`.

Thanks, Jon. What does "indexed" mean in that context?

By "index", I mean simply look up a key in an object (this is a common Lua term). string.find means "index the 'string' table with the key 'find'". Only tables have a built-in notion of indexing. Attempting to index anything else fails instantly, unless it has a metatable with an __index field (which strings by default do).

Gotcha. Thanks!