Skip to main content

Kernel-Scope Code Semantics

In some occasions, the code in taichi.js kernel-scope have slightly different semantics than normal Javascript code. These differences can sometimes cause bugs that are difficult to catch. This page aims to list these differences, so that you don't fall into these traps.

Assignment Semantics

In normal Javascript, when arrays and objects are assigned, the arrays/objects themselves are not copied. Rather, the target of the assignment merely maintains a reference to the same array/object. As an example, if we create a vector v initialized to [0.0, 1.0], assign v to v2, and modify v2, then v becomes modified as well.

// normal JS code:
let v = [0.0, 1.0]
let v2 = v
v2[0] = 2.0
console.log(v) // [2.0, 1.0]

This is not the bahavior in taichi.js kernels. In kernel-scope, after assigning v to v2, the vector which v represents are copied to v2, so that now v2 is its own vector, and any modifications to it will not affect v:

let k = ti.kernel(() => {
let v = [0.0, 1.0]
let v2 = v
v2[0] = 2.0
return v
})
console.log(await k()) // [0.0, 1.0]