英文:
How do I make a conditional return in WASM?
问题
以下是要翻译的内容:
我正在编写一个 WebAssembly 模块。
所以代码如下:
(module
(func (export "someCheck")
(param $n f64)
(result i32)
local.get $n
f64.const 2
f64.eq
)
)
这是一个简单的模块,返回 $n 是否等于 2 的结果。如果 $n 等于 2,则返回 1,否则返回 0。
这里对我来说一切都很清楚。
以下是用 JavaScript 编写的类似函数:
const someCheck = (n) => Number(n === 2)
但如何实现条件返回呢?
像这样,在 WebAssembly 中:
const someCheck = (n) => {
if (Number(n === 2))
return 1;
// 其他逻辑
return someRez;
}
谢谢!
注意
我认为有人可能需要这个表格。她对我很有帮助,尤其是关于栈的提示。
英文:
I am writing a wasm module.
So the code is:
(module
(func (export "someCheck")
(param $n f64)
(result i32)
local.get $n
f64.const 2
f64.eq
)
)
This is a simple module that returns the result of $n being equal to 2. If $n is 2 then return 1, otherwise return 0.
Here everything is clear to me.
Here is a similar function written in JavaScript:
const someCheck = (n) => Number(n === 2)
But how do I make a conditional return?
Like this, but in wasm:
const someCheck = (n) => {
if (Number(n === 2))
return 1;
// other logic
return someRez;
}
Thanks!
NOTE
I think someone might need this table. She helps me a lot. Especially stack hints
答案1
得分: 2
这可以通过0F
操作(return
,查看表格)来完成。
以下是一个示例,如果传入的参数是2,则返回数字5,否则返回数字10。
(module
(func (export "func")
(param $n i32)
(result i32)
local.get $n
i32.const 2
i32.eq
(if
(then
i32.const 5
return
)
)
i32.const 10
)
以下是JavaScript 的等效代码:
const func = (n) => {
if (n === 2) {
return 5;
}
return 10;
}
稍微复杂一点的示例,包括多个if/return语句:
(module
(func (export "func")
(param $n i32)
(result i32)
local.get $n
i32.const 2
i32.eq
(if
(then
i32.const 1
return
)
)
local.get $n
i32.const 3
i32.eq
(if
(then
i32.const 2
return
)
)
i32.const 3
)
)
以及其JavaScript 等效代码:
const func = (n) => {
if (n === 2) {
return 1
}
if (n === 3) {
return 2
}
return 3
}
英文:
This can be done with the 0F
operation (return
, see table).
Here is an example of a function that returns the number 5 if the passed parameter is 2, otherwise it returns the number 10.
(module
(func (export "func")
(param $n i32)
(result i32)
local.get $n
i32.const 2
i32.eq
(if
(then
i32.const 5
return
)
)
i32.const 10
)
Here is a JavaScript equivalent
const func = (n) => {
if (n === 2) {
return 5;
}
return 10;
}
A slightly more complex example with multiple if/returns:
(module
(func (export "func")
(param $n i32)
(result i32)
local.get $n
i32.const 2
i32.eq
(if
(then
i32.const 1
return
)
)
local.get $n
i32.const 3
i32.eq
(if
(then
i32.const 2
return
)
)
i32.const 3
)
)
And its JavaScript counterpart:
const func = (n) => {
if (n === 2) {
return 1
}
if (n === 3) {
return 2
}
return 3
}
答案2
得分: 1
WebAssembly有if
/else
控制结构的概念。
https://developer.mozilla.org/en-US/docs/WebAssembly/Reference/Control_flow/if...else
英文:
WebAssembly has the concept of if
/else
control structures.
https://developer.mozilla.org/en-US/docs/WebAssembly/Reference/Control_flow/if...else
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论