Nowadays, Lua
it-self has the local
and global
environment. We will be just talking about the global one. Therefore… actually Lua
keeps the access to this global variables within a hash table (dictionaries) within it’s name and value. This is actually already pretty efficient, but stills, really really slower than just accessing the stack (the one holding the local ones). Anyway, take in consideration that basically Lua
does not just keep them within a hash table, but it-self, it actually keep them in multiple environments to be more precise. However, we will ignore that in this section for the moment.
Anyway, there’s a lot of efficiency when it comes to this global access. One of them it’s that it simplifies it it-self since it doesn’t require further data structures for saving the global variables and that’s already really cool.
But why we said on the title _G
too? well, this “table” it’s actually giving you the advantage to manipulate the values inside of it, where the global ones are actually stored.
How this works? basically Lua
will store the environment it-self in a global variable called _G
global, now this is the one that let us get all of that. anyway, something interesting is that this is really similar to cyclic referencing
, since _G._G
it’s the same LOL (because _G
it is where stored the global(s)).
just some example code:
for _, global in pairs(_G) do print(global) end
(This is a pretty simple code and it’s actually on the wiki it-self. It’s a pretty good example to explain how this works) so basically here we will print any global access that basically, it is stored in the _G
environment, cool right?
anyway, now something interesting is that… just doing this:
foo = ... -- some value
It will get up the variable in the heap or the global environment (just as basic as that!) then we can later on access it with _G.foo
and it will get the value it-self! now. Something even more interesting is that we can actually do meta-programming within this environment! This is because _G
it’s just a normal table, and Lua
will treat it as that.
Therefore… we do as this for example:
local t = setmetatable(_G, {
__call = function(self, ...)
... -- code
end
})
_G() -- it will be alright!
Yessir, this is completely right and completely valid, so that’s just some basic go thru over the _G
hash table and so on!
Thanks for reading!
(This post was inspired by @Lil_SharkyBoy)