在Lua中,你能创建匿名代码块吗?

7
在诸如C语言之类的编程语言中,您可以创建匿名代码块,以将变量的范围限制在块内部。在Lua中是否也可以这样做呢?
如果可以,以下是C代码的Lua等效代码:
void function()
{
    {
        int i = 0;
        i = i + 1;
    }

    {
        int i = 10;
        i = i + 1;
    }
}

1
在Lua中,所有的块都是匿名的。一些函数定义的语法糖只是将函数定义与赋值结合起来的风格化方式。 - Tom Blodget
3个回答

9
您想使用do...end。请参考手册
注:本文档中的代码示例默认已经过调试,可直接使用。

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

6

1
运行匿名函数的步骤如下: (function(a,b) print(a+b) end)(1,4) 它输出了5。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接