Scope: Difference between revisions

From Legacy Roblox Wiki
Jump to navigationJump to search
>NXTBoy
Will finish later
>NXTBoy
Will finish later
(No difference)

Revision as of 19:35, 20 August 2010

Introduction

This tutorial will introduce you to scopes of Variables. It is recommended that you are familiar with the Variables and Functions tutorial.

Discussion

A scope is what can access a variable. Let's try, for example, printing the value of a variable that was declared in a function. The following will give us an error:

function myFunction()   
	myVariable = 64
end

print("myVariable is " .. myVariable)

The variable 'myVariable' was declared inside myFunction, and myVariable was created when myFunction was run. Once myFunction ends, myVariable no longer exists. That is why you can't "print" myVariable outside of this function.

How do you print myVariable?

You can declare outside of the function to have a "global scope."

myVariable = 64 -- this value is declared outside of the function
function myFunction()   
end
print("myVariable is " .. myVariable)

Or you will have to call the function so that the variables within the function don't get destroyed:

function myFunction()   
myVariable = 64
end
myFunction() -- the function is being called here
print("myVariable is " .. myVariable)

Local variables can keep variables within the scope of the function or environment it is declared in. Variable environments can also be set with getfenv and setfenv.

function myFunction()
local myVariable = 64
end
myFunction()
print("myVariable is ", myVariable) --> myVariable is nil

This outputs nil because the word 'local' prevented the variable from being accessible outside of the function's environment even when the function was called. Global variables can be set easily by removing the word local, but for even better control over a variables scope, you can use setfenv.

function myFunction()
function myFunction2()
print(a)
end
myFunction2()
print(a)
end
setfenv(myFunction, {a = 64,print=print, _G = unpack(_G)})
myFunction()
print(a)

This will output two values of 64, and will output one nil. The variable's environment was set to the function 'myFunction', and therefore the variable was also accessible by descendant environments (myFunction2). The setfenv function was called taking in two arguments, the environment in which the variable was to be placed in, and a table with the variables to be set. The variable 'a' was set, along with the reset for the global table.

See Also

Variables