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

What is "do", and is it different from regular functions?

Asked by 7 years ago

Like,

do
    print("idk")
end

What is the difference between just using regular code?

2 answers

Log in to vote
3
Answered by 7 years ago
Edited 7 years ago

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.

0
"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. chess123mate 5873 — 7y
0
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. chess123mate 5873 — 7y
0
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. chess123mate 5873 — 7y
Ad
Log in to vote
-1
Answered by 7 years ago

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.

0
That is not true, I have seen it multiple times in script i've come across, and clearly it does something. SebbyTheGODKid 198 — 7y
0
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. User#20279 0 — 7y
0
^ It's more common with loops, but it can be done by itself alone. TheeDeathCaster 2368 — 7y

Answer this question