Search code examples
duktape

How to run a whole js files multiple times using duk_pcall?


I want to use duk_pcall to do it, here is what I tried:

  • Firstly, I load the script file into a char* string.
  • Secondly, use duk_pcompile_string(ctx, 0, programBody) to compile it.
  • Then, I can use duk_pcall(ctx, 0) to call it once, and call duk_pop(ctx).

But when I try to use duk_pcall a second time, I failed.

Can you give me some advice about how to do it the right way?


Solution

  • duk_pcompile_string places the result on the TOS and duk_pcall executes the TOS (+ eventual parameters) and replaces all of that by the return value of the call.

    In order to make the function callable multiple times you have to duplicate the TOS insert the required parameter and then call that using the pcall. After the call remove the result from the stack. The original function should now be at the TOS again. Start over with what is written in this paragraph, to call it again.