lua-users home
lua-l archive

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


On 13/12/2011 21.39, Xavier Wang wrote:
2011/12/14 Luiz Henrique de Figueiredo<lhf@tecgraf.puc-rio.br>:
local a = (function(a, b) print "a statement" return a + b end)(10, 20) + 30

Lua 5.1 will create a new closure every time this statement is execute.
Lua 5.2 will not: it will resuse the closure.

Try the code below in each version:

for i=1,3 do
        local f = function(a, b) print "a statement" return a + b end
        local a = f(10, 20) + 30    + i
        print(f,a)
end


I mean, if Lua found a anonymous function don't assign to any value,
then just translate it into a new level with it's separate scope, like
this:

local a = (function(a, b) return a + b end)(10, 20) + 30
becomes:
do
    local a, b = 10, 20
    local ret = a  + b
end
local a = `ret` + 30

ret is in above scope. and its the only variable that "export" from
above scope. its will allow write a block that return a value. and can
be embed it into a expression.



Sometimes I've dreamed the following syntax would be supported:

-- do..end blocks can return values with "local return"s
local a = do
  local a, b = 10, 20
  -- "local return" makes the block to return its value
  -- instead of terminating the enclosing function
  local return a + b
end

But I don't know if this could cause other problems and is orthogonal to other features, besides being considered "useless fat" by Lua Team :-).

Now that 5.2 reuses closures maybe it may be made syntactic sugar for:

local a = (function()
  local a, b = 10, 20
  -- "local return" makes the block to return its value
  -- instead of terminating the enclosing function
  return a + b
end)()

but I see problems with this code transformation approach, for example what if the block contained a "non-local", i.e. plain, return?

Food for thought.	

Cheers.
-- Lorenzo