On Fri, Jun 16, 2017 at 08:18:10PM +0000, Jonathan Goble wrote:
> Let's break it down:
> > local string = ""
> The variable `string` is now an empty string and, in this scope, no longer
> references the `string` standard library.
> > print(string.format("%X", 16777216))
> Here, Lua first looks up `string.format`. While `string` no longer refers
> to the string standard library, it is an actual string, and strings (since
> Lua 5.1) have a metatable with an __index metamethod pointing to the actual
> string library (which isn't changed by your local `string` assignment, nor
> would an assignment to the global `string` affect it). So the lookup of
> `string.format` produces, via metamethod, the string standard library
> function `format`. From there, you can call it with whatever arguments you
> So why is it a bad idea? One, because indexing through a metamethod is
> slower than directly indexing the actual `string` table, and two, because
> shadowing a built-in global (whether with a global or local assignment) is
> usually a code smell (in any language) and generally shouldn't be done
> without a very good reason.
OTOH, using the string global is actually more like _G.string.find,
requiring two VM index operations. Whereas an index through a local (or
immediate) value is a single VM index operation; the loading and indexing of
the metatable is direcly implemented as compiled C code that doesn't require
stepping through the VM interpreter and so theoretically should be much
... and my hypothesis checks out:
Interesting! So my first point is invalid, but the second point (about shadowing built-ins being a generally bad idea) still stands.