Is there something like arguments.callee
of JavaScript for MoonScript?
Asked
Active
Viewed 187 times
1

Yu Hao
- 119,891
- 44
- 235
- 294

wenLiangcan
- 109
- 1
- 11
-
Is there a reason why you can't use regular named functions? Lua does not have a Javascript-like `arguments.callee` (and this is a good thing, IMO) – hugomg Jun 25 '14 at 03:46
-
@hugomg Because MoonScript do not support regular named functions. http://moonscript.org/reference/#function_literals – wenLiangcan Jun 25 '14 at 03:49
-
2@wenLiangcan You can make the example you linked to recursive by indenting the second line ... – siffiejoe Jun 25 '14 at 04:26
-
@hugomg Lua doesn't have named functions. They are all anonymous. Sure there are function definition statements but they are just "syntactic sugar" for an assignment from a function definition expression. In Lua, you can do `debug.getinfo(1,'f').func` as long as you're not in a tail call, which is determined by your caller. I don't know MoonScript. – Tom Blodget Jun 25 '14 at 04:26
-
1@siffiejoe A function can't _be_ recursive because it can't definitively refer to itself. A call chain can be recursive: the same function is called more than once in the call chain. But it would have to be through an upvalue or global reference. In the example you cite, with your modification, `my_function` is an upvalue in the body of the function. Initially, it refers to the function, but it can be changed before the function is called. – Tom Blodget Jun 25 '14 at 04:47
-
@TomBlodget Then don't change the upvalue and you get your recursive function. – siffiejoe Jun 25 '14 at 05:34
-
@siffiejoe Yes, that is very practical. My point is existential. There is a difference between a function that can be called recursively but depends on an external variable and one that does not. Since Lua doesn't have the JavaScript `arguments.callee` or equivalent, you can't define one that doesn't depend on an external variable. You can make sure that no other live scope has access to that variable. Or, you can just allow the external dependency to exist and it'll work recursively when the upvalue variable references the function value. – Tom Blodget Jun 25 '14 at 16:50
1 Answers
5
Since Moonscript functions are defined as local func; func = function() end
, they are all recursive. This will print 120:
recursive = (n) -> return n > 1 and n*recursive(n-1) or 1
print recursive 5
As far as I know, there is no arguments.calee
alternative, but I haven't seen cases where I'd need it either. Even Mozilla's docs say "there are nearly no cases where the same result cannot be achieved with named function expressions" about arguments.callee
.

Paul Kulchenko
- 25,884
- 3
- 38
- 56