lualua-table

Is there a way to use <const> inside a Lua table?


Since Lua 5.4, the <const> syntax lets us set const variables. I noticed that this doesn't transitively affect fields inside a table.

local x <const> = {
    a = {1,2,3},
    b = {5,6,7}
}

x = 5 -- error
x.a = 9 -- no error

The table x is const and cannot be reassigned, but fields inside the table can.

Is there any way to make the fields inside a table also const via syntax alone? I know that it's possible via the index and newindex metamethods, but I'm curious if it's possible with simple syntax like <const>.

I tried the following, but it produces a syntax error:


local x <const> = {
    a <const> = {1,2,3},
    b <const> = {5,6,7}
}

Solution

  • const is used to declare a local variable constant, but tables are not variables: they are objects (or values in Lua parlance). There are no immutable tables in Lua. In the OP code x is a constant variable initialized to hold a table as its value; no further assignments can be made to x. The value which x holds is a table, and that object is mutable.

    It is not possible in Lua to use const in the manner described in the OP question. In the posted code x is a (constant) variable to which is bound a table. In that table, a and b are not variables, but they are keys. In Lua a key (or an associative array index) is another value. But remember: values are not variables, rather variables store values. It may help to recall that x.a is just syntactic sugar for x["a"], i.e., the table x has a slot indexed by the value "a". Lua allows the const attribute to be associated with variables, but not values, so a and b cannot be made const.

    There may be some ways to simulate immutable tables using metatable magic, but I suspect that these would come with performance penalties which would defeat one of the reasons for using immutable objects in the first place. I would avoid this sort of thing. There may be some instances where it would be convenient to have immutable tables built into Lua, but if you really think that you need this you should probably consider whether another language is more appropriate for your problem.