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

后端 未结 2 1434
慢半拍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条回答
  •  天涯浪人
    2021-02-05 17:45

    The normal syntax for indexing a table is t[val]. For string keys only, Lua provides an alternate syntax, where t.foo is exactly equivalent to t["foo"]. This is purely a syntactical convenience, so-called 'syntax sugar'. It doesn't add functionality, it just gives you a less cluttered syntax for using strings as named fields.

    There are a lot of strings keys this won't work for:

    t["hello_world"] => t.hello_world  -- works
    t["hello world"] => t.hello world  -- oops, space in the string
    t["5 * 3"]       => t.5 * 3        -- oops
    t['[10]']        => t.[10]         -- oops
    

    Basically it only works if the string key would be a valid identifier.

    Again, tables are indexed via [], and in most cases you need to use them:

    t = {
       -- [key]           = value
       [10]               = "ten", -- number key, string value
       ["print function"] = print, -- string key, function value
       ["sub table"]      = {},    -- string key, table value
       [print]            = 111,   -- function key, number value
       ["foo"]            = 123,   -- string key, number value
    }
    

    Only if you're using a string key which would work as a valid identifier (no spaces, contains only word characters, numbers, or underlines, and doesn't begin with a number) can you use the shortcut syntax. For the table above, that would be only 'foo':

    t = {
       -- [key]           = value
       [10]               = "ten", -- number key, string value
       ["print function"] = print, -- string key, function value
       ["sub table"]      = {},    -- string key, table value
       [print]            = 111,   -- function key, number value
       foo                = 123,   -- string key, number value
    }
    

提交回复
热议问题