What does the do end scope does?

You probably seen this type of scope in scripting.

do
    print("hi")
end

From what I’ve heard, this just makes the code run in a scope, so that if you create a local variable in it, only codes inside that scope can access it. Is there any use case for this type of scope when scripting?

1 Like

Functionally? I suppose. You may find you need to run a separate bit of code from a loop, inside the loops iterations; this sounds extremely weird and edge-case, because it is. It’s so edge-case that I can’t even think of an example for it right now.

Either way, the primary use case I find I use it for is just… Structure. It adds some structure, organization, and a funky little collapsible scope of code that doesn’t need to be a function or run on a certain condition.

Hope this clears it up a bit, I was a bit foggy on this myself when I first learned about it too.

2 Likes

The use case for it is private variables. When you don’t want other variables with possibly the same name to mess you up or you just don’t want those vars in the global scope.

And do end creates a new scope, for example:

local Number = 10

do local Multi = 9; Number *= Multi end --makes a new scope

--cant access multi here but Number becomes 90

--a scope example is
function name()
   --this is where the scope begins for function name
end

for _, v in ipairs(...) do
    --this is where the scope begins for the for i, v loop
end

Not sure why people use it.

Edit 2:

3 Likes

This is how I use it, and I consider it to be one of the most practical things you can do with it. Sometimes you need to define a variable but you don’t want to see how it is defined.

local redParts = {}
for i, v in pairs(workspace:GetDescendants()) do
    if v:IsA("BasePart") and v.BrickColor == BrickColor.new("Bright red") then
        table.insert(redParts, v)
    end
end

In this example I know what redParts is, but if I’m just glancing over my script to find some function or something, the single variable takes up six lines of my vision and time.

local redParts do
redParts = {}
for i, v in pairs(workspace:GetDescendants()) do
    if v:IsA("BasePart") and v.BrickColor == BrickColor.new("Bright red") then
        table.insert(redParts, v)
    end
end

This helps out a lot because every scope can be minimized by using the little dropdown button on the left:

image
So now, my six lines boil down to just two very short, easily skimmed over lines.

1 Like