Reputation: 2580
I've started reading Seven More Programming Languages In Seven Weeks and Day One deals with Lua. I don't know much about Lua (yet!) but my first thought was, hmm, this seems to have quite a few similarities to JavaScript.
A way it isn't similar to JavaScript is quickly highlighted in a sidebar on Tail Cails. The following code:
function reverse(s, t)
if #s < 1 then return 1 end
first = string.sub(s, 1, 1)
rest = string.sub(2, 2, -1)
return reverse(rest, first .. t)
end
large = string.rep('hello ', 5000)
print(reverse(large, ''))
does indeed, as the book states, work fine in Lua but blow the stack when translated to JavaScript and run in the console of my Chrome browser.
A couple of questions arise for me then:
(1) Can anyone expand on the book's assertion that "Lua correctly optimizes the recursive call into a simple goto" to complete the calculation? What is going on under the hood in both languages that makes one capable of handling this operation, and thwarts the other?
and
(2) Relatedly, I guess, is there a good reason why JavaScript allows this kind of recursion to blow the stack? From a naive point of view it seems to me like if code in two high-level languages look almost identical, and there is a way to get it to work as intended at the lower level, you might as well as a language designer do what it takes to make it work. I'm assuming that it's not just because JavaScript is some kind of inferior language that it doesn't optimize its tail calls... is it?
Upvotes: 2
Views: 153
Reputation: 430
Tail Call Optimization is not supported in JavaScript (ES4). Also note that tail calls, are not always recursive.
See http://www.paulbarry.com/articles/2009/08/30/tail-call-optimization for a good article.
Also: http://duartes.org/gustavo/blog/post/tail-calls-optimization-es6/
Upvotes: 1