local _G = _G creates a direct memory reference to the global environment table, so that you can do _G["some variable"] directly to look up some variable or function globally which is slightly faster than having Lua look up the _G table internally.
Commonly used functions should still be localized individually, but don't overdo it.
i am still wondering about "local _G = _G", what's the point? (Again, i cant check myself what the "bytecode" looks like).
I'd like to know what the lua instructions are for this code:
Any variable that Lua cannot find locally, it will try to look it up in the "global environment table". The "global environment table" is this table that is normally accessed by using getfenv(0).
However, Lua offers a shortcut in that it predefines a global variable called _G that refers to this same global environment table. Hence you may assert that _G._G == _G
When you perform _G["whiz"], Lua first determines that _G isn't a local variable. So it looks up _G in the global environment table just like any other variable you try to access. It finds the _G variable in the global environment table, and does a table lookup on "whiz". This means there is 2 table lookups - one for "_G" (by Lua internally) and one for "whiz".
If you simply did "whiz", it would have been just one table lookup in the global environment table, but Lua would have to retrieve the global environment table first internally.
By doing local _G = _G, you store in a local variable the table reference to the global environment table. When you do _G["whiz"] then, it will find _G in a local variable, and do 1 table lookup to find "whiz". Hence doing _G["whiz"] is faster than doing "whiz" because the former doesn't attempt to look for the global environment table, it already has the _G table referenec stored in a local variable.
You can do "_G = nil", variables will still be looked up perfectly fine internally by Lua in the global environment table when you do "whiz" because the actual global environment table is always available via getfenv(0). _G is just a global variable like any other global, doing _G = nil merely nils out the 4 byte memory reference to itself in the global environment table, it doesn't wipe out the actual global environment table. (Meaning, you killed (global environment table)._G You cannot wipe out the (global environment table) but you can replace it by using setfenv())