Using the "do" Statement

I have been coding for a while, but I have recently started to notice that some of the super useful modules that people created use the do statement. I was wondering, why would you use

do
    -- some code here
end

instead of just typing the code without the do end statement like this:

-- the same code here without the do statement

It helps prevent memory leaks and keeps code more organized and tidy. When you create a new scope, all variables in that scope are there until the scope closes, to where they can be garbage collected peacefully. This means that in huge blocks of code without the do end statements, there are chances for variables to be made and then not cleaned up afterwards due to a strong reference or some other issue.

2 Likes

Yup.

Also, variables defined in the do end block cannot be accessed from outside.

local x = 123
do
    local x = 456
    local y = 789

    print(x) -- Prints: 456
    print(y) -- Prints: 789
end
print(x) -- Prints: 123
print(y) -- y is not defined.
1 Like