lua-users home
lua-l archive

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




On Sun, Aug 1 2021 at 09:16:57 PM +0800, 重归混沌 <findstrx@gmail.com> wrote:
But,the function g is actually optimized.

Maybe Lua team may has some rule for these cases.

Both the f and the g are being optimized in those examples. Note how the f function uses the LOADK instruction instead of GETUPVAL.

The `local a <const> = 1` in your original program is also optimized, transforming the `a == 1` into `1 == 1`. However, Lua doesn't optimize the `1 == 1` as you would expect. That's a separate problem that is unrelated to the constant variables.

This might be clearer if we add more variables to the program. In the following example, we can see that the bytecode for foo_const and foo_int are the same, and it is different from the bytecode code for foo_mut. Lua's optimizations get rid of the "a <const>" variable. All the places that use the "a<const>" are compiled as if they were the corresponding number instead (10).

-- Lua code --

function foo_mut()
   local a = 10
   local b = 20
   if a == 10 then
       return "hello"
   else
       return "world"
   end
end

function foo_const()
   local a <const> = 10
   local b = 20
   if a == 10 then
       return "hello"
   else
       return "world"
   end
end

function foo_int()
   local b = 20
   if 10 == 10 then
       return "hello"
   else
       return "world"
   end
end

-- Bytecode --

 function foo_mut:
     1 [2] LOADI 0 10
     2 [3] LOADI 1 20
     3 [4] EQI 0 10 0
     4 [4] JMP 3 ; to 8
     5 [5] LOADK 2 0 ; "hello"
     6 [5] RETURN1 2
     7 [5] JMP 2 ; to 10
     8 [7] LOADK 2 1 ; "world"
     9 [7] RETURN1 2
     10 [9] RETURN0

 function foo_const:
     1 [13] LOADI 0 20
     2 [14] LOADI 1 10
     3 [14] EQI 1 10 0
     4 [14] JMP 3 ; to 8
     5 [15] LOADK 1 0 ; "hello"
     6 [15] RETURN1 1
     7 [15] JMP 2 ; to 10
     8 [17] LOADK 1 1 ; "world"
     9 [17] RETURN1 1
     10 [19] RETURN0

 function foo_int:
     1 [22] LOADI 0 20
     2 [23] LOADI 1 10
     3 [23] EQI 1 10 0
     4 [23] JMP 3 ; to 8
     5 [24] LOADK 1 0 ; "hello"
     6 [24] RETURN1 1
     7 [24] JMP 2 ; to 10
     8 [26] LOADK 1 1 ; "world"
     9 [26] RETURN1 1
     10 [28] RETURN0