Scripting HelpersARCHIVE
A little piece of Roblox history. Preserved for everyone, one question at a time.Read about the archive →
✓ ANSWER ACCEPTED

What's the point of 'do' outside of a loop?

I took a peek at Stravant/StickMasterLuke's TweenCFModule, and found that much of the mid-section of the code was encapsulated by a do - end. What's the point? Organization? Thanks for any help! :)

1 answer

✓ Accepted answer

Part of it is organization, but the technical reason for it is that Lua uses do ... end to define generic 'blocks' of code. while and for loops use these inherently, although I'm not sure about the bytecode for repeat loops and if statements.

The consequence of this is that do ... end blocks create a layer of scope:

x = 5
do
	local x = 15
	print(x) --> 15
end
print(x) --> 5

And any other consequences you can draw from that. It's useful of you want to reuse variable names, although it's more useful to deny access to variables declared in the global scope of a script:

local board = Instance.new("BillboardGui", workspace.Player.Head)
board.Name = "Test"
do
	local f = Instance.new("Frame", board)
	f.Name = "Example"
	f.Size = UDim2.new(1,0,1,0)
	f.BackgroundColor3 = Color3.new()
	f.BackgroundTransparency = .5
	f.BorderSizePixel = 0

	local txt = Instance.new("TextLabel", f)
	--I think you get the idea.
end

print(board) --Test
print(f) --nil
print(txt) --nil

3 comments

0

"The consequence of this is that do ... end blocks create a layer of scope:" Upvoted

0

I've never actually known this till now. Upvoted!

0

Thanks so much, extremely helpful!

This discussion is preserved as it was. New answers, comments, and votes are closed.