Search code examples
printfassemblyscript

How do I write a printf() function in AssemblyScript?


I mostly need this for logging where I need to pass in arbitrary arguments (ints floats, objects).

One solution is to write

let i:i32 = 1;
let f:f32 = 1.1;
log ("Message "+i.toString()+" "+f.toString())

This is very awkward and verbose to write.

You can also have multiple log functions, again awkward

log_i (msg:string, i:i32);
log_i2 (msg:string, i:i32, i2:i32);
log_f (msg:string, f:f32);
etc

Seems like you cannot have a generic array that holds i32, f32 and objects at the same time. So not even sure how to pass in varargs. Maybe I can box them but it is again awkward without auto-boxing.

What would be a good solution for this straightforward usecase?


Solution

  • Simply use Typescript style Template strings.

    log (`Message ${i} and ${f}.`)
    

    Assemblyscript will automatically generate the toString() and string concatenate statements.

    1. Simple and concise
    2. More expressive logs rather than put all arguments at the end.
    3. No awkward function calls, varargs, etc.