How does the ROBLOX function 'do' work?

I am simply just trying to understand the point of the solo function ‘do’. I’ve seen it used across an array of scripts, but could never find an explanation of how it works, and if it’s more efficient in any way.

do
    -- My code here, usually in ModuleScripts
end

Not sure the correct terms I could use to find the specific function defintion page, but it can be linked, that’d be wonderful.

do isn’t a function. do end defines a new scope. lua-users wiki: Scope Tutorial

local hello = "hi"

do
     local world = "world"

     print(hello, world) --// "hi", "world"
end

print(hello, world) --// "hi", "nil"

world is nil in the outer scope.

5 Likes

It’s not a function, just syntax that marks a specific block of code.

It’s pretty much identical to this:

if (true) then
    -- Code
end
3 Likes

Interesting, so what could be useful about it besides preventing overlapped variables?

You should use do and end with while:

while true do

end

you should use then and end with if:

if true then

end

Really is no use. I use it for small organization so I can expand and close blocks of code, but there really is no reason to use it.

do end blocks don’t have much versatility because they don’t really do anything except create a new scope.

3 Likes