Skip to content

Arrays in Wasm

The AOT backend supports arrays inside functions: literals, indexing (0-based), len(), for-in, and push. There is one current limitation: a let at the top level is not yet supported (it would be lowered to a global); keep array code inside functions — locals work normally.

@export functions can accept and return single-level scalar arrays: [int], [bool], and [str]. The mirrored JS types are number[], boolean[], and string[], respectively. On the consumer side:

import init, { total, evens, shout } from './04-arrays.js';
await init();
total([1, 2, 3, 4]); // 10
evens([1, 2, 3, 4, 5, 6]); // [2, 4, 6]
shout(['a', 'b']); // ["a!", "b!"]

The example below shows the three exported functions and a pure-language demonstration block — calling total from fn demo() to verify behavior within Zolo before crossing the wasm boundary:

Arrays in @export: [int]→int, [int]→[int], and [str]→[str].

04-arrays.zolo
// Feature: arrays in AOT wasm + `@export` of array types
// Build (AOT, browser):
//   zolo build 32-webassembly/04-arrays.zolo --emit wasm --host browser --aot \
//     -o 32-webassembly/target/04-arrays.wasm
//
// In-language arrays work under --aot: literals, indexing (0-based), len(),
// for-in, and push. NOTE: a `let` at the top level isn't supported yet (it
// lowers to a global); keep array code inside a function (locals work).
//
// `@export fn`s can take/return one-level scalar arrays — [int], [bool], [str]:
//   import init, { total, evens, shout } from "./04-arrays.js"
//   await init()
//   total([1, 2, 3, 4])      // 10
//   evens([1, 2, 3, 4, 5, 6])// [2, 4, 6]
//   shout(["a", "b"])        // ["a!", "b!"]
// (number[] <-> [int], boolean[] <-> [bool], string[] <-> [str].)

@export fn total(xs: [int]) -> int {
  let mut s = 0
  for x in xs { s = s + x }
  return s
}

@export fn evens(xs: [int]) -> [int] {
  let mut o = []
  for x in xs {
    if x % 2 == 0 { o.push(x) }
  }
  return o
}

@export fn shout(xs: [str]) -> [str] {
  let mut o = []
  for s in xs { o.push("{s}!") }
  return o
}

// In-language demo (arrays used entirely inside a function):
fn demo() {
  let xs = [1, 2, 3, 4]
  print("sum = {total(xs)}")
}
demo()

// expected (run natively): sum = 10

Requires the Zolo CLI/host — open in the playground or run locally.

Challenge

Add a function @export fn sum_of_evens(xs: [int]) -> int that filters the even numbers and sums the result. Test it from JS with [1, 2, 3, 4, 5, 6] and confirm the return value is 12.

enespt-br