[Date Prev][Date Next][Thread Prev][Thread Next]
[Date Index]
[Thread Index]
- Subject: Re: upvals in Lua bytecode
- From: Xingzhi Pan <vengeance.storm@...>
- Date: Thu, 2 Jun 2011 00:13:43 -0700
Oh mine, it is a bit unintuitive to leave "global" as default. Thank
you people!
Harry
On Wed, Jun 1, 2011 at 11:49 PM, François Perrad
<francois.perrad@gadz.org> wrote:
>
>
> 2011/6/2 Xingzhi Pan <vengeance.storm@gmail.com>
>>
>> Hi,
>>
>> I'm using luac -l to observe the bytecode of the following Lua source:
>>
>> 1 function fo (i)
>> 2 uv = 0
>> 3 function fi1 ()
>> 4 print(uv)
>> 5 uv = 1
>> 6 print(uv)
>> 7 end
>> 8 function fi2 ()
>> 9 print(uv)
>> 10 uv = 2
>> 11 print(uv)
>> 12 end
>> 13 if i == 1 then return fi1 end
>> 14 if i == 2 then return fi2 end
>> 15 end
>> 16
>>
>> And this is what I get:
>>
>> main <../upval.lua:0,0> (3 instructions, 12 bytes at 0x100101050)
>> 0+ params, 2 slots, 0 upvalues, 0 locals, 1 constant, 1 function
>> 1 [15] CLOSURE 0 0 ; 0x1001011f0
>> 2 [1] SETGLOBAL 0 -1 ; fo
>> 3 [15] RETURN 0 1
>>
>> function <../upval.lua:1,15> (15 instructions, 60 bytes at 0x1001011f0)
>> 1 param, 2 slots, 0 upvalues, 1 local, 6 constants, 2 functions
>> 1 [2] LOADK 1 -2 ; 0
>> 2 [2] SETGLOBAL 1 -1 ; uv
>> 3 [7] CLOSURE 1 0 ; 0x1001015c0
>> 4 [3] SETGLOBAL 1 -3 ; fi1
>> 5 [12] CLOSURE 1 1 ; 0x1001017c0
>> 6 [8] SETGLOBAL 1 -4 ; fi2
>> 7 [13] EQ 0 0 -5 ; - 1
>> 8 [13] JMP 2 ; to 11
>> 9 [13] GETGLOBAL 1 -3 ; fi1
>> 10 [13] RETURN 1 2
>> 11 [14] EQ 0 0 -6 ; - 2
>> 12 [14] JMP 2 ; to 15
>> 13 [14] GETGLOBAL 1 -4 ; fi2
>> 14 [14] RETURN 1 2
>> 15 [15] RETURN 0 1
>>
>> function <../upval.lua:3,7> (9 instructions, 36 bytes at 0x1001015c0)
>> 0 params, 2 slots, 0 upvalues, 0 locals, 3 constants, 0 functions
>> 1 [4] GETGLOBAL 0 -1 ; print
>> 2 [4] GETGLOBAL 1 -2 ; uv
>> 3 [4] CALL 0 2 1
>> 4 [5] LOADK 0 -3 ; 1
>> 5 [5] SETGLOBAL 0 -2 ; uv
>> 6 [6] GETGLOBAL 0 -1 ; print
>> 7 [6] GETGLOBAL 1 -2 ; uv
>> 8 [6] CALL 0 2 1
>> 9 [7] RETURN 0 1
>>
>> function <../upval.lua:8,12> (9 instructions, 36 bytes at 0x1001017c0)
>> 0 params, 2 slots, 0 upvalues, 0 locals, 3 constants, 0 functions
>> 1 [9] GETGLOBAL 0 -1 ; print
>> 2 [9] GETGLOBAL 1 -2 ; uv
>> 3 [9] CALL 0 2 1
>> 4 [10] LOADK 0 -3 ; 2
>> 5 [10] SETGLOBAL 0 -2 ; uv
>> 6 [11] GETGLOBAL 0 -1 ; print
>> 7 [11] GETGLOBAL 1 -2 ; uv
>> 8 [11] CALL 0 2 1
>> 9 [12] RETURN 0 1
>>
>> So my question is that for inner functions fi1 and fi2, why GETGLOBAL
>> and SETGLOBAL, rather than GETUPVAL and SETUPVAL, are used? Isn't uv
>> an upvalue?
>
> Currently, uv is a global variable.
> If you want an upvalue, you must use 'local uv = 0' line 2.
>
> François
>
>>
>> Also, it shows "0 upvalues" for these 2 functions, where I thought
>> should be one.
>>
>> Thanks,
>> Xingzhi 'Harry' Pan
>>
>
>
--
Pan, Xingzhi
http://www.panxingzhi.net