How and when can I use the do - end?

As in the title, I would like to know what the use of this?

do
    -- code
end

Makes all the code inside of it “invisible” to the rest of the script. I usually use this when tweening things so instead of doing local tween1, local tween2, I can use a “do block” and I’ll be able to use the same variable name as much as I want.

I believe that local scopes like this are used to clean up your code, however I’m probably wrong about this, but it’s how I use it.

1 Like

Creating locals that do not need to be exposed to outer scopes.

For instance:

local get_x, set_x
do
    local x = 0
    
    function get_x()
        return x
    end

    function set_x(value)
        x = value
    end
end

print(get_x()) -- 0
set_x(5)
print(get_x()) -- 5

Here we are limiting the scope of x. The variable is still alive because it is available in the getters and setters get_x and set_x respectively as upvalues.

3 Likes