[RBX.Lua] HasTEK Tutorial A1-Function environment(s).
May 13, 2017 21:30:26 GMT
Josh, goulstem, and 1 more like this
Post by Bit on May 13, 2017 21:30:26 GMT
Okay, let us begin today's session.
This time, we've got to talk about function environments.
Let's start off simple.
What ARE function environments?
Simply put, they are tables where global variables are stored at.
That means, you can modify a function's GLOBAL variables by modifying its environment.
Please do note, as stated, it only contains global variables, not local ones.
Now that we know that, we should know next, HOW can we use them?
Pretty simple to explain, there are some built-in functions, setfenv() and getfenv(),
which allow to manipulate a function's environment.
Such as in...
local print=print --You'll see why this is needed later on...
local f=function()
local UnmoddedVariable=5
print(UnmoddedVariable)
print(ModdedVariable)
end
local f2=function()
local UnmoddedVariable="Hi"
print(UnmoddedVariable)
print(ModdedVariable)
end
local env={} --Make a new environment table for f1
env.ModdedVariable=7 --Put a variable inside of it.
setfenv(f,env) --Set the function's environment.
f() --Run the function #1.
-->5
-->7
local env2=getfenv(f2) --Get the second function's environment.
env2.ModdedVariable=9 --Set the variable to something.
f2()--Run the function #2
-->Hi
-->9
Now you might wonder why I localized print, the answer is simple.
This was required so that function1 had access to it.
When setting a function's env, it no longer has access to built-in variables, such as game, print, etc.
Yet, as mentioned above, these functions can not affect locals, and due to the way scopes work,the function can access the localized print just fine.
This "problem" only happens with setfenv(f,env), and not with modifying an already existing environment.
These functions can also be used with a number, and when done so, they affect the function that is on that stack level.
To not make this too long, we'll cover that another day.
All you need to know about that for now, is that if you pass 1 as the first argument, it'll return/set (depending on the function) the env. of the function calling set/getfenv().
And if you use with a 0 as a first argument, it'll change the environment of the whole thread.
For example, and to finish this lesson;
local f1=function()
getfenv(0).Hello="World" --Set a new variable at the thread, called Hello and containing "World"
print(Hello) --This works due to Hello becoming a global variable for the thread.
end
f1()
-->World
print(Hello) --Hello is now a global! You can call it from anywhere!
-->World
That's all for today.
Goodbye!