What does 'do' do?

Hello developers, I’ve a lot of open-source modules have these lines:

local Tab do

--do stuffs
end

or

do 
--do stuffs
end

I’m very confused, someone can explain it to me?

Using do makes the code inside it unaccessible to outer-scopes.

Example:

local changeName

do 
  local _name = "Mystxry12"
  
  function changeName(name) 
    _name = name
    
    return name
  end
end

The _name variable is defined inside the do block and hence cannot be accessed by code outside it.

So wt to do if we want to change _name?

Simple. By using changeName function, as it was declared before running the code inside do code block. So u can do:

local newName = changeName("Stellqr")

Using the above code u changed the variable _name without directly changing the variable itself.

TL;DR: Makes all the code inside of do “invisible” to the rest of the script.

5 Likes

But, why can’t just declare the variable inside the function?

Do if I am correct just runs the code inside of it. Not really sure as I have never used it.

1 Like

U can do that by making it a global variable, but thats bad for performance so i avoided it. The issue with declaring it locally inside of do is that, then the function cant b acessed outside the do block.

1 Like

I see thx for the explaination.

1 Like

Organization is another big benefit. Read my post at the link since I don’t really want to type it all out again on my cell phone keyboard.

1 Like