Hello. My primary language is Python and I’m a little confused on how scope works in Roblox Studio, and I was hoping someone might be able to clear it up for me.
How exactly do local variables work in Roblox Studio? Because they provide a different result than what I’d expect with Python. More specifically, a lower scope can read, but not modify, a higher scope. I’ll give an example.
In Roblox Studio, I have the following code:
local myValue = true
local function ChangeValue()
myValue = false
end
print(myValue)
ChangeValue()
print(myValue)
This code prints true and false. However, when I do the same thing in Python:
You have declared a local var in the highest scope, effectivly making it a global variable. If it was in a lower scope it would not be accessible to the entire script.
Interesting, any reason why it’s done this way? I don’t know of another programming language that functions like that, and it seems to make the return statement redundant.
Because scopes are scopes and are meant to be relative to their current context by convention.
Python is an anomaly because it doesn’t listen to this convention at all, due to it not having a definition keyword. Rather it depends on a helper keyword:
Which is completely backwards from basically any other language. It’s actually conventional to have variables inherited from the upper scope of any given function, unless it is executed in a fresh environment.
Is there any purpose for global variables inside of Roblox Studio then, aside from declaring them in a lower scope? Since unlike stand-alone Lua, they don’t index to _G.
Global variables can be used to hold constants throughout your code, make data easily accessible, hold general variables that you might later change in multiple functions, etc.
_G was a somewhat hacky part of Lua, and Roblox defines values to a sandboxed part of the environment.
And local does have a use for scope control. You can define variables in the current scope with locals, whereas subverting that local prefix would define a new variable or overwrite a global one.
Unlike in python, you can define same-name variables with 0 worry for errors, except that you may be reading data from a variable (ex.) called "Pets" and overwrite that with a new local Pets = {} in your function (or loop) and then the data you expected to be within "Pets" is now no longer there as it is now reading the local scope’s "Pets" variable first.