Search code examples
lualua-table

Why can't a Lua table be initialized with a table as one of its keys?


Why does this print bar and baz, like it is supposed to:

local foo = {}
foo[ { "bar", "baz" } ] = 42

for k1, v1 in pairs(foo) do
  for k2, v2 in pairs(k1) do
    print(v2)
  end
end

While initializing the foo table with the { "bar", "baz" } table as its key directly gives the error input:1: '}' expected near '=', at least on the Lua demo website?:

local foo = { { "bar", "baz" } = 42 }

for k1, v1 in pairs(foo) do
  for k2, v2 in pairs(k1) do
    print(v2)
  end
end

Solution

  • In the table constructor, use [] to surround the key:

    local foo = { [{ "bar", "baz" }] = 42 }
    --            ^                ^
    

    Refer to Lua 5.4 Reference Manual 3.4.9 - Table Constructors. You can only leave out the square brackets around a key if it is a Lua identifier (name).