Lua的一般运行时会优化表查找吗?

表能否像命名空间一样,在运行之前扩展其字段,以避免索引表?我计划使用Lua的5.3.3编译器。例如:

local Types = {
    A = 1,
    B = 2,
    C = 3
};

print(Types.A);

这能变成:

print(1);

或者类似于(但可能更好的):

local A = 1;
print(A);

直接吗?

点赞
用户5675002
用户5675002

不,Lua 会如实运行代码。这就是编译器简洁性的代价。

请看 luac 的输出:

main <2.lua:0,0> (8 instructions at 0x235bb10)
0+ params, 3 slots, 1 upvalue, 1 local, 7 constants, 0 functions
    1   [1] NEWTABLE    0 0 3
    2   [2] SETTABLE    0 -1 -2 ; "A" 1
    3   [3] SETTABLE    0 -3 -4 ; "B" 2
    4   [4] SETTABLE    0 -5 -6 ; "C" 3
    5   [7] GETTABUP    1 0 -7  ; _ENV "print"
    6   [7] GETTABLE    2 0 -1  ; "A"
    7   [7] CALL        1 2 1
    8   [7] RETURN      0 1
2017-05-10 15:39:23
用户107090
用户107090

你可以将 Types 设置为一个临时表来解决全局变量名的问题:

local Types = {
    A = 1,
    B = 2,
    C = 3
}

do
    local print = print
    local _ENV = Types
    print(A)
end

但是请考虑一下为什么你需要这样做。请注意,在设置 _ENV 之前需要保存 print

2017-05-10 16:35:36