# 變數

WebAssembly 中可定義區域變數與全域變數。區域變數定義在函式之中，必須使用 `local` 預先宣告，變數的預設值對整數來說是 `0`，對浮點數來說是 `+0.`

``````int a = 10;
int b = 20;
int c = a + b;
``````

``````(module
(import "env" "log" (func \$log (param i32)))
(func \$main
(local \$a i32) (local \$b i32) (local \$c i32)
i32.const 10
set_local \$a
i32.const 20
set_local \$b
get_local \$a
get_local \$b
set_local \$c
get_local \$c
call \$log
)
(start \$main)
)
``````

``````(module
(import "env" "log" (func \$log (param i32)))
(func \$main
(local \$a i32) (local \$b i32) (local \$c i32)
i32.const 10
tee_local \$a
i32.const 20
tee_local \$b
tee_local \$c
call \$log
)
(start \$main)
)
``````

``````(module
(import "env" "log" (func \$log (param f32)))
(global \$PI f32 (f32.const 3.14159))
(func \$main
get_global \$PI
call \$log
)
(start \$main)
)
``````

``````(module
(import "env" "log" (func \$log (param f32)))
(global \$PI (mut f32) (f32.const 3.14159))
(func \$main
get_global \$PI
call \$log
f32.const 3.14
set_global \$PI
get_global \$PI
call \$log
)
(start \$main)
)
``````

``````(module
(import "env" "PI" (global \$PI f32))
(import "env" "log" (func \$log (param f32)))
(func \$main
get_global \$PI
call \$log
)
(start \$main)
)
``````

JavaScript 的部份，匯入物件上有對應的特性就可以匯入：

``````const importObj = {
env: {
PI : 3.14159,
log(n) {
console.log(n);
}
}
};
WebAssembly.instantiateStreaming(fetch('program.wasm'), importObj);
``````

``````(module
(import "env" "PI" (global \$PI (mut f32)))
(import "env" "log" (func \$log (param f32)))
(func \$main
get_global \$PI
call \$log
f32.const 3.14
set_global \$PI
get_global \$PI
call \$log
)
(start \$main)
)
``````

JavaScript 的部份，匯入物件上對應的特性，必須是 `WebAssembly.Global` 實例：

``````const importObj = {
env: {
PI : new WebAssembly.Global({value : 'f32', mutable : true}, 3.14159),
log(n) {
console.log(n);
}
}
};
WebAssembly.instantiateStreaming(fetch('program.wasm'), importObj)
.then(_ => {
console.log(importObj.env.PI.value);
});
``````

``````(module
(global \$PI f32 (f32.const 3.14159))
(export "PI" (global \$PI))
(func \$nop)
)
``````

（在這個範例中，`(func \$nop)` 是必須的，似乎要匯出東西的模組，至少得有一個函式的樣子，拿掉該行會發生錯誤！）

``````WebAssembly.instantiateStreaming(fetch('program.wasm'))
.then(prog => console.log(prog.instance.exports.PI.value));
``````