kettle11 / tangle

Radically simple multiplayer / networked WebAssembly
MIT License
1.18k stars 37 forks source link

Cannot read property: `_in_call_that_will_be_reverted` #16

Open km19809 opened 1 year ago

km19809 commented 1 year ago

Description https://github.com/kettle11/tangle/blob/9abd44380dfad5af209bf2e7d9d17f09aab39397/tangle_ts/src/tangle.ts#L92-L97 When I call imported JS functions, this becomes undefined. So, this._in_call_that_will_be_reverted cannot be read.

What I did I ran the example counter but in Zig instead of AssemblyScript.

my_wasm.zig ```zig var num: f64 = 0.0; extern fn report_number_change(n: f64) void; export fn increment( val: f64) void{ num += val; report_number_change(num); } export fn multiply( val: f64) void{ num *= val; report_number_change(num); } ```

However, I doubt that is a Zig-related problem. As I know, the value of the this keyword depends on its context. Then, what is the value of this, if I call a function in a WASM?

To check that, I modified tangle.js:

              const r = importValue(...args);
              console.warn(`${importName}():${this}`)
              if (this?._in_call_that_will_be_reverted) {
                return r;
              }

Then it says: image The first 4 calls are exports.increment(1)s, and others are exports.multiply.callAndRevert(3)s.

This shows that wrapping a function call did not help! https://github.com/kettle11/tangle/blob/9abd44380dfad5af209bf2e7d9d17f09aab39397/tangle_ts/src/tangle.ts#L328-L331

Additional note I tried an arrow function, but it made this._in_call_that_will_be_reverted undefined, and this was not a Tangle instance. (it was a function.) moduleImports[importName] = (...args) => { I want to figure out why this happens, but the keyword this was nearly impossible to search.

km19809 commented 1 year ago

Ok, things get complicated. We want this to be an instance of Tangle. It is easy to solve: we can use bind(tangle). However, instantiation of Tangle needs a time_machine instance. Because time_machine.setup instantiate the WASM binary, we need to modify imported functions before the setup. It is something like the chicken-egg problem. For now, we are trying to access a property of an uninitialized instance. It is hard to solve...

DiogoNeves commented 1 year ago

Maybe I misunderstood the issue. When is the function containing _in_call_that_will_be_reverted called? If you bind, it should still have access to the time_machine once it's set? Options I'm thinking:

I'm sure there are better solutions, I'm just curious what would help :)

km19809 commented 1 year ago

The function containing _in_call_that_will_be_reverted is called when I call an imported function. In addition, the function does not need a time_machine instance. I prefer your 3rd option, but I am not sure.