lua-users home
lua-l archive

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


David Kastrup <dak@gnu.org> writes:

> Dirk Laurie <dpl@sun.ac.za> writes:
>
>> In Lua you must take care if you want to define a global recursive 
>> function.  Thus:
>>
>> do  local fact
>>     fact = function(x) if x<2 then return 1 else return x*fact(x-1) end end
>>     fac = fact
>>     end
>> fact = "Napoleon escaped from Elba."
>> print(fac(5)) --> 120
>>
>> You can't omit any of that padding: create a local variable, then 
>> assign it to a global variable, all in an enclosing block.
>
> do
>   local function fact(x) if x<2 then return 1 else return x*fact(x-1)
>   end end
>   fac = fact
> end
> fact = "Napoleon escaped from Elba."
> print(fac(5))
>
> is a bit more compact on the eyes.

Actually, you can also do

function fac(x)
local function fact(x) if x<2 then return 1 else return x*fact(x-1) end end
return fact(x)
end

though I can't vouch for its efficiency.

-- 
David Kastrup