What is "do end" used for?

An example of this beeing used:

do
    local p = Instance.new('Part')
    p.Touched:connect(function() print("Touched") end)
end

do
    local p = Instance.new('Part')
    p.Touched:connect(function() print(p) end)
end

Source of code snippet: PSA: Connections can memory leak Instances!

I tried searching Roblox API but couldn’t find anything.
I assume it just executes whats inside of it. But then whats the purpose of it?

5 Likes

Literally speaking, it does and then ends. Code inside of a do just executes in a new local scope. Basically, it allows you to separate the p variables in that example. So the p in the first do won’t accidentally be reused when it’s not needed in any other scope. The post that code came from is using it to show how garbage collection works.

do
    local x = 5
end

print(x)

Essentially, x won’t be available outside the do, so this will print nil.

16 Likes

But then whats the purpose of it?

In it’s essence, the “do… end” are just indicators of what code lies within what section of a particular script.

If this helps as a comparison, here is an example of a loop in Java:

for (int i = 0; i < 10; i++) {
      // whatever code you want in the loop
}

whereas the Lua “equivalent” would replace the { and } with do and end, respectively.

for (i = 0, 10, 1) do
      // whatever code you want in the loop
end

Hope this adds on a little understanding from what steven said above!

4 Likes

Why can’t you just do:

local x = 5

print(x)

?

1 Like

You can, and by all means do. However, if you’re working with variable scope and garbage collection, do end’s are very helpful to not mix up variables with the same names. Most of the times, you won’t use and don’t need to use it. I’d say it’s used so infrequently you don’t even need it or need to care about it.

Quoting from Programming in Lua : 4.2 :

We can delimit a block explicitly, bracketing it with the keywords do - end . These do blocks can be useful when you need finer control over the scope of one or more local variables

3 Likes