TypeScriptToLua: C stack overflow when using await in a loop

Hello,

I’ve encountered a “C stack overflow” error while running the following TypeScript code which gets transpiled to Lua using TypeScriptToLua: for (let i = 0; i < 40; i++) { await delay(0.1); print('times:', i); } The function delay is an asynchronous function that returns a Promise that resolves after the specified delay. The print function logs the current iteration to the console.

The issue occurs when the loop reaches the 36th iteration (i=35), at which point the program crashes with a “C stack overflow” error. The expected behavior would be for the loop to successfully complete all 40 iterations without any issues.

I’ve tried debugging the issue on my end but haven’t been able to find a workaround. I’ve also ensured that the issue is not due to any memory leaks, high CPU usage, or problems with the delay function or the Lua runtime.

I’m using TypeScriptToLua version 1.20.1 and running the resulting Lua code in environment Warcraft III

Any help on this issue would be greatly appreciated.

Thank you!

About this issue

  • Original URL
  • State: closed
  • Created 9 months ago
  • Comments: 15 (13 by maintainers)

Commits related to this issue

Most upvoted comments

Thanks for the fixes! I have released a new version 1.24.0 with your PRs.

with some effort could probably be made tail recursive.

I’ve opened a PR that fixes the issue: https://github.com/TypeScriptToLua/TypeScriptToLua/pull/1530

Besides some other optimizations, I’ve did exactly that!

I think ideally it wouldn’t rely on tail call optimization which is likely to be brittle, but on an explicit iterative pump loop like:

An explicit loop would indeed be better, however I don’t see a way to adequately implement it keeping all of the JS Promise invariants. It’s probably possible but would result in a very large and complex spaghetti code I guess.