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
8 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
8 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:

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
0
"The consequence of this is that do ... end blocks create a layer of scope:" Upvoted Validark 1580 — 8y
0
I've never actually known this till now. Upvoted! Spongocardo 1991 — 8y
0
Thanks so much, extremely helpful! saenae 318 — 8y
Ad

Answer this question