Why I can't print Variables with _G

thats works on lua:

C1 = {"A"} --I shorted the names to just C for ease of typing this example.
C2 = {"B"}
C3 = {"C"}
C4 = {"D"}
C5 = {"E"}
for i=1, 5 do
local v = "C"..tostring(i)
print(_G[v][1])
end

But don’t work on roblox studio?

Because unlike vanilla Lua, Luau does not store global variables in global _G table due to sandboxing and security reasons. Every script thread has its own global environment stored separately behind a metatable that table returned by getfenv has.

You will have to use getfenv() instead of _G to get the variables you want. However, be warned that calling getfenv will disable most optimizations made by Luau in the background:

C1 = {"A"}
C2 = {"B"}
C3 = {"C"}
C4 = {"D"}
C5 = {"E"}

local env = getfenv()
for i = 1, 5 do
    local v = "C"..tostring(i)
    print(env[v][1])
end
2 Likes