Consider the following pseudocode:
function make_counter(start: i32) {
let mut count: i32 = start;
function increase() {
count += 1;
print(count);
return increase
}
return increase
}
let counter = make_counter()
counter() // 1
counter() // 2
How should similar code be compiled into WebAssembly?
My main question is, where should the variables be stored? Where should the functions be stored?
- Should variables be stored in global?
But every time make_counter
is called, there will be one more variable. Do I need to statically analyze how many times this function is called?
- Should functions be defined in table?
Dynamically called functions need to be defined in the table as element, and there isn't no way to call them through function pointers. Moreover, tables cannot be dynamically expanded in WebAssembly, and function pointers cannot be returned.
let counter = make_counter(); counter(); counter()
is equivalent tolet counter = make_counter(); counter()()
or even justmake_counter()()()
? $\endgroup$confuse
thandoubt
. $\endgroup$