How to print the length of an array in AssemblyScript / Near?
Asked Answered
T

1

7

I'm experimenting with simple assembly scripts on near and cannot seem to find a way to print the length of an array. Here's the smallest repro:

  let a = new Array<string>();
  logging.log(a.length.toString());

Doesn't compile with

ERROR TS2339: Property 'toString' does not exist on type 'i32'.

   logging.log(a.length.toString());
                        ~~~~~~~~
 in assembly/main.ts(171,23)

While toString() clearly exists on i32, e.g. the following snippet compiles and works:

  let a: i32 = 5;
  logging.log(a.toString());
Thiourea answered 11/9, 2019 at 22:51 Comment(0)
F
8

The problem is that assemblyscript type resolver cannot resolve certain kind of expressions, but this issue has been fixed here https://github.com/AssemblyScript/assemblyscript/pull/726 in upstream assemblyscript. We will fix this for smart contracts when we update the compiler. For now, the workaround is to use a temporary variable:

let a = new Array<string>();
let l = a.length;
logging.log(l.toString());
Fanfaron answered 11/9, 2019 at 23:15 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.