Scope

From Legacy Roblox Wiki
Revision as of 00:12, 7 October 2008 by >Mindraker
Jump to navigationJump to search

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)

See Also

Variables

GMod Wiki