lua-users home
lua-l archive

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]


On Mon, May 30, 2022 at 1:04 PM Ryan Starrett <pyryanggg@gmail.com> wrote:
This has been a small debate in a couple of my Lua circles for a little while. I've never quite understood the thoughts behind this new feature. Today, I took some preliminary observations into the bytecode behind 'const' and non-constant counter-parts. 

What I learned when doing this, is that constant locals which are associated with immutable values will behave more like a preprocessor macro than a position on the stack.

For example, printing a constant local defined as "my number" then printing it will produce the following bytecode:
0+ params, 2 slots, 1 upvalue, 0 locals, 2 constants, 0 functions
        1       [1]     VARARGPREP      0
        2       [2]     GETTABUP        0 0 0   ; _ENV "print"
        3       [2]     LOADK           1 1     ; "my number"
        4       [2]     CALL            0 2 1   ; 1 in 0 out
        5       [2]     RETURN          0 1 1   ; 0 out
Which is absent from the MOVE instruction from the non-const counter-part, so LOADK puts the value of the constant local directly into the instances of the local, instead of MOVE taking the value from the local.

Conversely, when a mutable value like a table is associated with a constant local, there are no bytecode differences, which means that a const local for a table is essentially identical to a non-const local, minus compile-time semantics like reassignment.

I know Lua is typically constrained on features because it wishes to preserve small binary sizes, but the const feature seems redundant with my current understanding. At this point, I don't know why it was added. Why was it added?

The rationale is reasonably well-documented in the mailing list archives: the underlying behavior was necessary to implement to-be-closed variables, so it didn't add overhead to expose <const> as a feature in the parser. Some developers like having the restriction on reassignment (it's the same semantics as JS const) so it's very much a "why not?" kind of thing.

/s/ Adam