I was examining some code, and I saw something that started with "do" and nothing else. It looked like a normal loop or something, but without anything special. What does this do?
Example:
hi = "hello"
do
local hi = "yo"
print(hi)
end
print(hi)
I was examining some code, and I saw something that started with "do" and nothing else. It looked like a normal loop or something, but without anything special. What does this do?
Example:
hi = "hello"
do
local hi = "yo"
print(hi)
end
print(hi)
What you're referring to is a do-end block. They come in the format below:
do
-- code block
end
So what's the advantage? do-end allows you to delimit a code block whenever you want. This is especially useful because delimiting a code block creates a new scope to place local variables in, should you ever require them.
Here's an example of this...
local a = 1
do
local a = 3
print("a = " .. a) -- prints a = 3
end
print("a = " .. a) -- prints a = 1
The scope of the variable a inside of the do-end block in my example is only within the do-end block. If you run the code, you can confirm that the variable's scope doesn't extend past the block.
This discussion is preserved as it was. New answers, comments, and votes are closed.
1 comment
It's very useful for controlled scopes.