【问题标题】:How to assign an item in a table definition to another item within the same table?如何将表定义中的项目分配给同一个表中的另一个项目?
【发布时间】:2019-08-20 22:29:25
【问题描述】:

我试图将表格的大括号定义中的一个项目分配给之前定义的另一个项目。但是 Lua 说,一旦在其定义中引用它,它就找不到表本身。

这是我想要实现的一个示例:

local t = {
    a = 1,
    b = 2,
    c = t.a + t.b
}

一旦接近t.a,Lua 将找不到t 并回复错误。

如何在t 内定义c 时引用t.at.b不离开大括号定义

【问题讨论】:

    标签: lua lua-table


    【解决方案1】:

    尴尬,但是:

    local t
    do
        local a = 1
        local b = 2
    
        t = {a, b, c = a + b}           
    end
    
    print(t.c) -- 3
    

    如果没有 do/end 块,ab 变量将在 t 之外可见。

    据我所知,没有直接的方法可以引用 ab,除非 1) 这些变量预先存在(上例)或 2) 表构建完成后。

    【讨论】:

      【解决方案2】:

      正如你提出的问题,你不能。

      The order of the assignments in a constructor is undefined。”

      因此,“先前定义”不是表构造函数中的概念。

      还有,“The assignment statement first evaluates all its expressions and only then the assignments are performed。”

      还有,“The scope of a local variable begins at the first statement after its declaration”。

      因此,无法引用语句结尾之前代码中显示的局部变量tt 将绑定到先前声明的变量或名为 t 的全局变量。

      【讨论】:

        猜你喜欢
        • 2017-08-25
        • 2019-11-06
        • 1970-01-01
        • 2014-07-21
        • 2021-11-23
        • 1970-01-01
        • 2015-06-04
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多