Like,
do
print("idk")
end
What is the difference between just using regular code?
Like,
do
print("idk")
end
What is the difference between just using regular code?
do, end is used to create a new scope in a script. This means when you modify a variable or create a local variable inside a do scope the variable will default back to whatever it was before do was called.
myVariable = 5
do
local myVariable = 3
print(myVariable)
end
print(myVariable)
Returns "3" then "5."
do
local myVariable = 3
print(myVariable)
end
print(myVariable)
Returns "3" then "nil."
This can be used to prevent memory leaks for unused variables and temporarily change a variable. Read more here.
Alternatively, you could use do, end to organize your code. For example, place all of your global variables inside a do, end scope so that those lines of code collapse. You'll have an easier time scrolling through your script.
That is not how “do” works. “do” is used for a thing called loops, which you can read about here.
If you’re thinking “do” is supposed to run code or something, it doesn’t do that. The code runs automatically unless it’s in some function or etc.
That is not true, I have seen it multiple times in script i've come across, and clearly it does something.
Oh. That's strange. I have NEVER seen anyone make use it like that. I think it's meant for loops but since there's nothing but "do" in the line, it just runs the script. Maybe it can be used to separate lines of code? I don't know.
^ It's more common with loops, but it can be done by itself alone.
This discussion is preserved as it was. New answers, comments, and votes are closed.
3 comments
"when you modify a variable... inside a 'do' scope the variable will default back to whatever it was before 'do' was called" is not correct. Line 3 (first script) creates a new variable, so you never end up modifying 'myVariable' from line 1. Thus, if you took out the 'local' on line 3, "3" and "3" would be printed.
Also, you can use 'do return end' to return early without commenting the rest of the scope (including the outermost one, allowing you to effectively disable the rest of a Script). Note that if you create a function that uses local variables defined in 'do end', they will not be deleted from memory when lua hits the 'end' until the function is no longer being referenced.
To clarify something: if on line 3 you say "local myVariable = myVariable + 2", the "local myVariable" is a new variable, but "myVariable + 2" refers to the one from line 1 because a local variable only exists after its declaration/initial assignment.