Why does nothing happen when you try to enumerate _G?

I know this has probably been answered before. But I am just discovering this unexpected result.

Simply put, if I were to run the following lua code outside of Roblox

for k,v in pairs(_G) do
    print(k,v)
end

It would print out a list of all of the items in the global table, including things like “print”, “math”, “table”, etc.

But If I ran that in a Roblox lua script, or just ran it in the command bar at the bottom of Roblox Studio, it does not print a single thing. Telling me that for some reason, _G is empty?
Kinda strange that it would do that. But I know there is probably a known answer.
I was concearned if maybe _G was non-functional, which would be sad. Because honestly it’s best use is making your own global tables full of utility functions, without any need to type a long path to a module.

to be clear, you’d still have to call require() and type a long path, but yea…

2 Likes

The reason is because there’s a race condition. The enumeration code runs before the things are inserted into _G, so there is nothing there to enumerate over.

The solution? Don’t use _G because it leads to nasty things like this.

Probably because Roblox did something to hide it for the global functions. Should be known as sandboxing from my knowledge.

When initializing the default globals table, the tables are protected from modification:

  • All libraries (string, math, etc.) are marked as readonly
  • The string metatable is marked as readonly
  • The global table itself is marked as readonly

_G should still work for custom stuff.

:eyes:

image

vscode and roblox LSP +1

1 Like

hmmmm.

Yea I heard about the sandboxing thing actually.

Also, how does vscode work with roblox??? :sweat_smile:
I mean, that sounds cool. I’ll look into it, thanks.

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.