What is the 'do' statement’s function?

Asked

Viewed 488 times

6

What the 'do' alone waits and makes?

do
   ...
end

3 answers

8


Does nothing :)

It starts a block of commands that must be executed together. The block is obviously finished by end.

It is very common to use with command such as: if (actually uses the then in place of do), while, for and functions (although in this case the do is implicit), where it is common to have several lines.

It is important to note that it generates scope, so the variables created in it only exist within it. So it can be used only to generate scope.

do
    local x = 1
    y = x + 1
end
print(y) -- não poderia mandar imprimir x

I put in the Github for future reference.

In called languages C-like, like Javascript, PHP, Java, C#, etc. it would be the equivalent of the key opener {, as well as the end would be the key lock }.

Page with tutorial and examples.

  • When I create a variable in a statement without "do" or "then" (if case) declared then the variable is global in the current block - that’s what I understood. That’s right?

  • This is something else. All variables are global unless they are declared as local. The local scope is defined by some rules that determine the command block.

  • Um... all the command pads on the Moon generate scopes, right? In Ecmascript the blocks do not generate new scope of variables, only functions, but the declarations const and let define variables in the block itself.

4

The main function and usefulness of the do is to create a new scope: local variables defined within that scope do not escape out of it.

One reason to use a new scope is not to pollute the rest of the program.

A more sophisticated reason is to create and maintain private state:

do
  local n=0
   function count() n=n+1 print(n) end
end

count is visible outside the scope but n nay.

3

You should use this sequence right after a while. It serves to limit the chunk of code that will run inside the loop.

For example:

a=10

while( a < 20 ) 
do    
print("valor de a:", a)    
a = a+1 
end

Browser other questions tagged

You are not signed in. Login or sign up in order to post.