lua-users home
lua-l archive

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


-----BEGIN PGP SIGNED MESSAGE-----
Hash: SHA1

David Kastrup wrote:
> Ok, call me stupid, but a recursive function in my book would be one
> that can call itself and is self-contained.
[...]
> then this is _not_ a self-contained recursive function, since it relies
> on calling itself through the variable named fact.

Well, I'm not entire sure what such a thing would be *useful* for, but
you should be able to achieve what you want using the following foul hack:

function fact(n)
  local self = debug.getinfo(1, "f").func
  if (n>1) then
    return n*self(n-1)
  end
  return 1
end

But this will be horribly, *horribly* slower.

If what you want is to prevent people from fiddling with the innards of
your recursive function, would not something like this suffice?

local fact
do
  local fact = fact
  fact = function(n)
    ...same function body here...
  end
end

Now the 'fact' that's called by the function is safely enclosed in an
upvalue in an isolated scope and can't be modified. Will that do?

- --
David Given
dg@cowlark.com
-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.4.9 (Cygwin)
Comment: Using GnuPG with Mozilla - http://enigmail.mozdev.org

iEYEARECAAYFAknHpt8ACgkQf9E0noFvlzgljwCgvmfVC8igP21XFUeaL95FJqdh
An4AoICiY+msdG2HV/h+QyhR/0ZnIIj4
=QDkK
-----END PGP SIGNATURE-----