local t = {}
for i=1,10 do
t[i] = i
end
编译后代码
1 [1] NEWTABLE 0 0 0
2 [2] LOADK 1 -1 ; 1
3 [2] LOADK 2 -2 ; 10
4 [2] LOADK 3 -1 ; 1
5 [2] FORPREP 1 1 ; to 7
6 [3] SETTABLE 0 4 4
7 [2] FORLOOP 1 -2 ; to 6
8 [4] RETURN 0 1
第二种初始化方式
local t = {1,2,3,4,5,6,7,8,9,10}
1 [1] NEWTABLE 0 10 0
2 [1] LOADK 1 -1 ; 1
3 [1] LOADK 2 -2 ; 2
4 [1] LOADK 3 -3 ; 3
5 [1] LOADK 4 -4 ; 4
6 [1] LOADK 5 -5 ; 5
7 [1] LOADK 6 -6 ; 6
8 [1] LOADK 7 -7 ; 7
9 [1] LOADK 8 -8 ; 8
10 [1] LOADK 9 -9 ; 9
11 [1] LOADK 10 -10 ; 10
12 [1] SETLIST 0 10 1 ; 1
13 [1] RETURN 0 1
可以看出第一种调用的是SETTABLE第二种调用的是SETIST, 第二种方式一次性申请空间,然后设置值,避免多次赋值导致TABLE的增长引起空间的重新分配。 case OP_SETLIST: {
int n = GETARG_B(i);
int c = GETARG_C(i);
int last;
Table *h;
if (n == 0) {
n = cast_int(L->top - ra) - 1;
L->top = L->ci->top;
}
if (c == 0) c = cast_int(*pc++);
runtime_check(L, ttistable(ra));
h = hvalue(ra);
last = ((c-1)*LFIELDS_PER_FLUSH) + n;
if (last > h->sizearray) /* needs more space? */
luaH_resizearray(L, h, last); /* pre-alloc it at once */
for (; n > 0; n--) {
TValue *val = ra+n;
setobj2t(L, luaH_setnum(L, h, last--), val);
luaC_barriert(L, h, val);
}
continue;
}