Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can you create anonymous code blocks in Lua?

Tags:

lua

anonymous

In programming languages such as C you can create an anonymous code block to limit the scope of variables to inside the block can the same be done with Lua?

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

void function()
{
    {
        int i = 0;
        i = i + 1;
    }

    {
        int i = 10;
        i = i + 1;
    }
}
like image 896
Puddler Avatar asked Jan 11 '16 00:01

Puddler


People also ask

How do you comment on Lua?

A comment starts with a double hyphen ( -- ) anywhere outside a string. They run until the end of the line. You can comment out a full block of code by surrounding it with --[[ and --]] . To uncomment the same block, simply add another hyphen to the first enclosure, as in ---[[ .

What is a code blocks JavaScript?

JavaScript Code Blocks JavaScript statements can be grouped together in code blocks, inside curly brackets {...}. The purpose of code blocks is to define statements to be executed together.


1 Answers

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

A block can be explicitly delimited to produce a single statement:

stat ::= do block end

Explicit blocks are useful to control the scope of variable declarations. Explicit blocks are also sometimes used to add a return or break statement 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
like image 143
Tim Cooper Avatar answered Sep 29 '22 09:09

Tim Cooper