What does 'do'
alone expect and do?
do
...
end
What does 'do'
alone expect and do?
do
...
end
Do nothing:)
It starts a block of commands that must be run together. The block is obviously terminated by end
.
It is very common to use with command, such as if
(actually uses then
instead of do
), while
, for
and functions (although in this case% is implicit), where it is common to have multiple rows.
It is important to note that it generates scope, so the variables created in it only exist inside 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
In languages called C-like , such as JavaScript, PHP, Java, C #, etc. it would be the equivalent of the open key do
, just as {
would be the key end
.
The main function and utility of 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 status:
do
local n=0
function count() n=n+1 print(n) end
end
count
is visible out of scope but n
not.
You should use this sequence right after a while. It serves to limit the snippet of code that will be executed within the loop.
For example:
a=10
while( a < 20 )
do
print("valor de a:", a)
a = a+1
end