Can you create anonymous blocks of code in Lua?

In programming languages ​​such as C, you can create an anonymous block of code to limit the scope of variables within a block, can you do the same with Lua?

If so, what will be the Lua equivalent of the following C code?

void function() { { int i = 0; i = i + 1; } { int i = 10; i = i + 1; } } 
+5
source share
3 answers

You want to use do...end . From manual :

A block can be explicitly split to create a single statement:

 stat ::= do block end 

Explicit blocks are useful for managing the scope of a variable declaration. Explicit blocks are also sometimes used to add return or break in the middle of another block.

 function fn() do local i = 0 i = i + 1 end do local i = 10 i = i + 1 end end 
+6
source

You can distinguish between a block with the keywords do and end .

Link: Programming in Lua

+5
source

An anonymous function is launched as follows: (function(a,b) print(a+b) end)(1,4)

It outputs 5.

0
source

Source: https://habr.com/ru/post/1240298/


All Articles