Ad
Log in to vote
1

"do...end" statement [closed]

Asked by 3 years ago

I was examining some code, and I saw something that started with "do" and nothing else. It looked like a normal loop or something, but without anything special. What does this do?

Example:

hi = "hello"
do
    local hi = "yo"
    print(hi)
end
print(hi)

Locked by BlueTaslem

This question has been locked to preserve its current state and prevent spam and unwanted comments and answers.

Hi.

Looks like you're using an ad blocker.

That's fine...

No, it really is.

Just, I mean, we put a lot of work into this site, you know?

It would be really really appreciated if you would turn off your ad blocker for our website...

We tried really hard to make our ads as unobtrusive as possible.

If you really hate ads, would you consider a $2 donation via Patreon?

Here's the link.

We love you. We hope you love us too.

.

..

...

Now back to your regularly scheduled Scripting Helpers....

...

..

.

1 answer

Log in to vote
5
Answered by
Unclear 1641 Administrator
3 years ago

What you're referring to is a do-end block. They come in the format below:

do
-- code block
end

So what's the advantage? do-end allows you to delimit a code block whenever you want. This is especially useful because delimiting a code block creates a new scope to place local variables in, should you ever require them.

Here's an example of this...

local a = 1

do
    local a = 3
    print("a = " .. a) -- prints a = 3
end

print("a = " .. a) -- prints a = 1

The scope of the variable a inside of the do-end block in my example is only within the do-end block. If you run the code, you can confirm that the variable's scope doesn't extend past the block.

2
It's very useful for controlled scopes. Quenty 200 — 3y
Ad
Ad