How does (do) work by itself?

I noticed that a few users haved used this and I’m curious as to how it works. And whether this can be applied to my coding.

----------------------------------------------------------------------------------

do
-- do stuff..
end

-- instead of 

while true do
-- do stuff..
end

I couldn’t find any questions related to this in the forum here or the developer site(API reference). I could sift through the Lua manual but I highly doubt it’s in there considering it used it in the very beginning without explaining what it does.

So what does it do?

1 Like

The only thing it does is create a new scope. It’s useful if you’re creating variables temporarily that you don’t want to hold onto. For instance, if you’re constructing an object with lots of children, you have to create each of those children objects and parent it into your instance, but you might not want to keep those variables around after they’re created since they’re not needed anymore.

For instance:

local model = Instance.new("Model")
-- Create stuff in it:
do
   local obj = Instance.new("ObjectValue")
   obj.Name = "Something"
   obj.Value = workspace
   obj.Parent = model
end

-- ... do stuff with `model`. From here the `obj` variable is no longer useable and will be GC'd soon.

I have coded entire games and not used do ... end in them. It’s not often that they’re actually going to give you a lot of value.

4 Likes

So it’s like creating a function then disconnecting(erasing) it after it’s completed it’s task. So that it doesn’t take space in the memory. Thanks!