Scripting Helpers is winding down operations and is now read-only. More info→
Ad
Log in to vote
0

What does putting the word "local" before words like "function",etc. do?

Asked by 9 years ago

So I've been watching scripting tutorials online. Some of the commentators used "local" before words like "function","player",etc. When do you put it and why do you use it?

2 answers

Log in to vote
2
Answered by
dyler3 1510 Moderation Voter
9 years ago

Using the word local restricts the variable to a specific scope. It's kinda hard to explain with words, so here's an example:

local example="chirp"

function ex1()
    local example="moo"
    return example
end

function ex2()
    local example="oink"
    return example
end

print(example) --prints out chirp
print(ex1()) --prints out moo
print(ex2()) --prints out oink

In this example, each function has a different scope than the other, and they both have a different scope than the first variable. When they print, they all print out different things because they are all defining the variable "example" in different scopes than one another, because. Using a function creates it's own scope, thus leading to separation of the variables.

For more information on this, check out this page, or this page!


So that's basically what they do, but what exactly would you use it for?

Well, you can use this knowledge to your advantage in many ways. It can be used in functions that fire more than once to keep the variables separated from one another. Or it can be used in loops, to define a new, clean variable for each iteration. Overall, "localizing" variables can help in many aspects of coding.


Anyways, I hope I helped you out a bit. If you have any questions, please leave a comment below. Again, hope I helped :P

Ad
Log in to vote
2
Answered by 9 years ago

The keyword local denotes a variable or function so that it can only be used within its current scope. If a local variable is within a function, only that function can use it and if access is attempted from outside of its scope, an error will be thrown.

Example:

options = {"Scripting", "Helpers", "Is", "Awesome"}

function printer()
    local word = options[math.random(1,4)]
    print(word)
end

printer()

print(word) -- this will error because it is outside of the scope that word is used in

If you need more help understanding what I am explaining, please visit the scripting glossary or The Roblox Wiki.

Answer this question