lua-users home
lua-l archive

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


It had somehow never hit home to me that the top level of a Lua program
is a chunk. Because of this I had been enclosing my programs within
do ... end structures so that I could use local variables at the top level
( sledgehammers for nuts, as the programs were tiny, but that is not
the point ). Then I experimented, writing ( in Lua 5.2beta )

    local x = 8
    print(x) 

This ran fine, so all those do ... ends had been unnecessary. Disassembly
gives

    local x = 8
    --[[
         1 LOADK     0 -1 ; 8
    --]]
    print(x)
    --[[
         2 GETTABUP  1 0 -2 ; _ENV "print"
         3 MOVE      2 0
         4 CALL      1 2 1
         5 RETURN    0 1
    --]]

whereas disassembly of

    x = 8
    print(x)

gives

    x = 8
    --[[
         1 SETTABUP  0 -1 -2 ; _ENV "x" 8
    --]]
    print(x)
    --[[
         2 GETTABUP  0 0 -3 ; _ENV "print"
         3 GETTABUP  1 0 -1 ; _ENV "x"
         4 CALL      0 2 1
         5 RETURN    0 1
    --]]

I do not have to worry about all those extra do ... end structures because
disassembly of 

    do
     local x = 8
     print(x)
    end

gives

    do
    local x = 8
    --[[
         1 LOADK     0 -1 ; 8
    --]]
    print(x)
    --[[
         2 GETTABUP  1 0 -2 ; _ENV "print"
         3 MOVE      2 0
         4 CALL      1 2 1
    --]]
    end
    --[[
         5 RETURN    0 1
    --]]

- exactly the same bytecode as if the do ... end were not there.

I expect all this is not news to seasoned Lua users, but I thought the
disassembly listings might entertain. 

-- 
Gavin Wraith (gavin@wra1th.plus.com)
Home page: http://www.wra1th.plus.com/