lua-users home
lua-l archive

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


On Wed, May 20, 2020 at 4:51 PM Andrea <andrea.l.vitali@gmail.com> wrote:
> what are the reasons why <const> is necessary in Lua?
> does this enable optimized and faster bytecode? (I hope so)

As far as I understand, it was introduced just because <close> need
it, and it was for free. However, there is a "Constant elimination
mechanism":

local debug <const> = false
local x = debug or 'x'
print(x)

is translated to (output of luac -l)

0+ params, 3 slots, 1 upvalue, 1 local, 2 constants, 0 functions
    1    [1]    VARARGPREP    0
    2    [2]    LOADK        0 0    ; "x"
    3    [3]    GETTABUP     1 0 1    ; _ENV "print"
    4    [3]    MOVE         2 0
    5    [3]    CALL         1 2 1    ; 1 in 0 out
    6    [3]    RETURN       1 1 1    ; 0 out

while without <const>:

0+ params, 4 slots, 1 upvalue, 2 locals, 2 constants, 0 functions
    1    [1]    VARARGPREP    0
    2    [1]    LOADFALSE    0
    3    [2]    TESTSET      1 0 1
    4    [2]    JMP          1    ; to 6
    5    [2]    LOADK        1 0    ; "x"
    6    [3]    GETTABUP     2 0 1    ; _ENV "print"
    7    [3]    MOVE         3 1
    8    [3]    CALL         2 2 1    ; 1 in 0 out
    9    [3]    RETURN       2 1 1    ; 0 out

However last time I checked this kind of optimization are not always
made. I think that for now is just a promise of future optimization.