lua-users home
lua-l archive

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


On Mon, Jun 15, 2015 at 8:44 AM, Jinhua Luo <luajit.io@gmail.com> wrote:
> Hi All,
>
> The reference says "Notice that each execution of a local statement defines
> new local variables", however, does it make sense to statements with the
> same variable name?
> Even the lua parser creates new variables, only the last one is visible.
> For example,
>
> local val = 1
> local val = 1
> local val = 1
> print(val)
>
> The output from luac is:
> 0+ params, 5 slots, 1 upvalue, 3 locals, 2 constants, 0 functions
>     1    [1]    LOADK        0 -1    ; 1
>     2    [2]    LOADK        1 -1    ; 1
>     3    [3]    LOADK        2 -1    ; 1
>     4    [4]    GETTABUP     3 0 -2    ; _ENV "print"
>     5    [4]    MOVE         4 2
>     6    [4]    CALL         3 2 1
>     7    [4]    RETURN       0 1
> The print only sees the last one, while the first two are useless.
> So why the parser do not recognize this case and keep only one variable
> instance? Is there some special consideration?
>
>
> Regards,
> Jinhua Luo

It does if you have more code:

local x, y = getPosition()
render(x, y)
--...
local x, y = getSpeed()
doOtherThingsWith(x, y)

It's even more important if you create a closure in between those definitions.

-- 
Sent from my Game Boy.