lua-users home
lua-l archive

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


Dirk Laurie wrote:
On Wed, Dec 29, 2010 at 09:30:28PM +0200, Lorenzo Donati wrote:
Dirk Laurie wrote:
On Wed, Dec 29, 2010 at 09:22:36AM +0200, Dirk Laurie wrote:
Because of the need for a local name for the function, you can't define
an anonymous recursive function, e.g. for use in an argument list.
Wouldn't this idiom suffice?

fac = (function()
	local function fact(x) if x<2 then return 1 else return x*fact(x-1) end end
	return fact
end)()
fact = "Napoleon escaped from Elba."
print(fac(5)) --> 120


It took me a minute to figure out why it works, but many idioms are like that.

It's got this over the "Y constructor" that 'fact' remains a function
of one argument.  But is it easier to read?

Dirk





Well, probably its main advantage is that it is a fairly "standard" Lua idiom (and quite a general one) to turn a statement into an expression .

As for its readability, it could be improved by suitable indenting/spacing, but _it is_ verbose indeed.

After a while one gets accustomed to spot it if it is suitably indented:


fac = (function() 	-- begin of closure factory
   local function fact(x)
      if x<2 then return 1 else return x*fact(x-1) end
   end
   return fact		-- returns the closure
end)()	-- end of closure factory + closure creation


of course it depends on the context whether it is readable enough.


Other typical uses:
local hasNormallyEnded, result1_or_errMsg, result2 = -- add more results if necessary
   pcall( function() 	-- 'try'
         -- Protected block ('try' block).
         -- If the protected block terminates normally,
-- all its results are returned from pcall (result1, result2, etc.).
      end
   )
if not hasNormallyEnded then	-- 'catch'
   -- error handler ('catch' block)
end


Regards

--
Lorenzo