Search code examples
lualua-table

How to assign an item in a table definition to another item within the same table?


I tried to assign an item within a curly-bracket definition of a table to another item which was defined previously. But Lua says it cannot find the table itself once referring to it within its definition.

Here's an example of what I'm trying to achieve:

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

Once approaching t.a, Lua will fail to find t and reply with an error.

How can I reference t.a and t.b while defining c within t without leaving the curly bracket definition?


Solution

  • Awkward, but:

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

    Without the do/end block, the a and b variables would be visible outside of t.

    To my knowledge, there’s no direct way to refer to a and b, unless either 1) those variables exist beforehand (above example) or 2) once the table construction is complete.