[英]Does general Lua runtimes optimize table lookups?
像名稱空間那樣使用的表可以在運行之前擴展其字段,以避免為表建立索引嗎? 我計划使用Lua的5.3.3編譯器。 例如:
local Types = {
A = 1,
B = 2,
C = 3
};
print(Types.A);
這可以變成:
print(1);
或類似(但可能更好)的東西:
local A = 1;
print(A);
直?
不,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
您可以將“ Types
設置為臨時表來解析全局名稱:
local Types = {
A = 1,
B = 2,
C = 3
}
do
local print = print
local _ENV = Types
print(A)
end
但是請仔細考慮為什么要這樣做。 注意設置_ENV
之前需要保存print
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.