What is ‘local [variable name] do”?

So I was reading some CoreScripts and I often see the ‘do’ expression used like this:

local [variable name] do
end

The only thing I understand about ‘do’ is when I use it for

while true do
end

or

for i,v in pairs(table) do
end

So how does “local [variable name] do” do or work exactly?

It doesn’t “do” anything.

do end in luau denotes a block.

local x do

end

is the same as

local x
do

end

The main thing a block does is keep variables in it from being defined outside of it. In this example, x is outside the block, so it can be used inside or outside of it, but if you were to do

do
    local x = 5
end
print(x) -- nil

You’ll get nil since x is defined in the block.

Further examples:

local x do
	x = 5
	print(x) -- 5
end
print(x) -- 5
for i = 1, 5 do
    local x = i
end
print(x) -- nil
while example do -- assume example is defined somewhere
    local x = 5
end
print(x) -- nil

The main takeaway from this should be that local variables defined within “do end,” regardless of where it’s used, are unable to be used after the “end”

3 Likes

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.