Scripting Helpers is winding down operations and is now read-only. More info→
Ad
Log in to vote
4

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

Asked by
saenae 318 Moderation Voter
9 years ago

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

Log in to vote
5
Answered by
adark 5487 Badge of Merit Moderation Voter Community Moderator
9 years ago

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:

1x = 5
2do
3    local x = 15
4    print(x) --> 15
5end
6print(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:

01local board = Instance.new("BillboardGui", workspace.Player.Head)
02board.Name = "Test"
03do
04    local f = Instance.new("Frame", board)
05    f.Name = "Example"
06    f.Size = UDim2.new(1,0,1,0)
07    f.BackgroundColor3 = Color3.new()
08    f.BackgroundTransparency = .5
09    f.BorderSizePixel = 0
10 
11    local txt = Instance.new("TextLabel", f)
12    --I think you get the idea.
13end
14 
15print(board) --Test
16print(f) --nil
17print(txt) --nil
0
"The consequence of this is that do ... end blocks create a layer of scope:" Upvoted Validark 1580 — 9y
0
I've never actually known this till now. Upvoted! Spongocardo 1991 — 9y
0
Thanks so much, extremely helpful! saenae 318 — 9y
Ad

Answer this question