How to create a function that knows how many times it has been called, without returning content value?

It is like a get method in counter but does not return content. The use case of this is I want to implement a function use along with cetz package in the environment of canvas function. Since canvas only accepts array type, I cannot use context to get my counter values. I can think of two ways: manually update a local variable and make my function to read the value every times it has been called, or create a function that utilize the ctx of cetz context. Both ways are very complex, the first one is tedious to type every time I call that function, the latter requires update the definition of the function if the internal of cetz changes their syntax. How I can do this?

Sounds very close to what was asked just a few hours ago: How can I save a coordinate in Cetz?.

Something like this?

#import "@preview/cetz:0.3.4"
#cetz.canvas({
  import cetz.draw: *
  let func(pos) = {
    set-ctx(ctx => ctx + (my-func: ctx.at("my-func", default: 0) + 1))
    circle(pos)
    get-ctx(ctx => content(())[#ctx.my-func])
  }
  func((0, 0))
  func((3, 0))
})

image

3 Likes

Ah I see, that’s how set-ctx interaction works. Thank You.

1 Like