getsenv

Gets a script's environment table.

Syntax

getsenv(script: LocalScript | ModuleScript | Script) -> table?

Parameters

ParameterTypeDescription
scriptLocalScript, ModuleScript, or client ScriptThe script

Returns

TypeDescription
table?The script's global environment, or nil if it is unavailable

Description

getsenv returns the script's global environment. It does not include local variables and returns nil when the environment is unavailable.

Example

local scripts = getrunningscripts()
if #scripts > 0 then
    local env = getsenv(scripts[1])

    if env then
        print("Globals in script:")
        for key, value in pairs(env) do
            print("-", key, "=", type(value))
        end
    end
end

Accessing Script Variables

local function getScriptVariable(scriptName, varName)
    for _, script in ipairs(getrunningscripts()) do
        if script.Name == scriptName then
            local env = getsenv(script)
            return env and env[varName]
        end
    end
    return nil
end

local playerData = getScriptVariable("MainScript", "PlayerData")
if playerData then
    print("Found player data!")
end

Modifying Script Variables

local targetScript = getrunningscripts()[1]
local env = targetScript and getsenv(targetScript)

if targetScript and env then
    -- Modify a variable
    env.SomeFlag = true

    -- Call a function from the script
    if env.SomeFunction then
        env.SomeFunction()
    end
else
    warn("No running script environment was available")
end