Lua: implicit table creation with string keys - why the extra brackets?

后端 未结 2 1538
慢半拍i
慢半拍i 2021-02-05 17:03

Say that you want to create a Lua table, and all its keys are valid lua identifiers. Then you can use the key=value syntax:

local niceTable = { I=1,         


        
2条回答
  •  萌比男神i
    2021-02-05 17:40

    They identify the contained string as a key in the resulting table. The first form, you could consider as equal to

    local niceTable = {}
    niceTable.I = 1;
    niceTable.like = 1;
    

    The second form is equal to

    local operators = {}
    operators['*'] = "Why";
    operators['+'] = "The";
    

    The difference is purely syntactic sugar, except where the first one uses identifiers, so it has to follow the identifier rules, such as doesn't start with a number and interpret-time constant, and the second form uses any old string, so it can be determined at runtime, for example, and a string that's not a legal identifier. However, the result is fundamentally the same. The need for the brackets is easily explained.

    local var = 5;
    local table = {
        var = 5;
    };
    -- table.var = 5;
    

    Here, var is the identifier, not the variable.

    local table = {
        [var] = 5;
    };
    -- table[5] = 5;
    

    Here, var is the variable, not the identifier.

提交回复
热议问题