I am currently writing code to make a sort of Zig ↔ JS bridge thanks to WASM.
But I face this issue : some JS function have facultative arguments, with a default value.
I wrap them with a C ABI compatible JS function, but what is the most efficient way to indicate whether one argument should be used or not ?
My first guess, for boolean, was to use an u8 with false → 0, true → 1, null → 2. But this is a waste of resources and does not apply to other types.
My second guess was to use a mask to indicate which values need to be used or not. For example, if the function have four optional arguments, I can add an extra argument mask = 0b00001011 to tell the JS wrapper to not use the 3rd argument.
Is there a more efficient or proper way to do it ?
I would try to reify the problem by introducing an intermediate JS function with all parameters mandatory, and to define your function with optional arguments in terms of that one.
Something like this:
function f(a, b=3) {
g(a, b);
}
function g(a, b) {
console.log(a,b);
}
And then crossing the ABI with g instead of f. That would avoid the need for any tricks.
Do you need varargs? Also do you need both way communication?
I am not good with js/wasm so do you have more examples how it looks on code level?
Does any part of your functions written in js?
The problem with this solution is that I need to modify f, wich I can’t in some case.
For example, if i want to use the function document.body.addEventListener(). EventTarget: addEventListener() method - Web APIs | MDN
The two first arguments are mandatory, but the 3rd is optional. And depending on the value of the first argument and the browser used, the default value can differ !
Yes, varargs sounds like a solution to this problem. Is it possible with the C ABI ???
I am preparing a good example with real code.
It is probably not what I reccomend but yeah you can do C variadic Documentation - The Zig Programming Language
0 Comments
Log in to join the conversation.No comments yet. Be the first to share your thoughts.