Hello there,
I have a question regarding the output of a context query. What I want to do is create a variable that calculates the sum of all headings (level: 1) in my document. I then want to use this variable to set the number of columns in a table.
Please have a look at this reprex:
// a simple array
#let a = (1, 2, 3)
#let a_length = a.len()
#type(a_length) // a_length is of type int
// my case
= First
= Second
= Third
#let my_counter = context {
let chapters = query(heading.where(level: 1))
let chap_len = chapters.len()
chap_len
}
#type(my_counter) // my_counter is of type content
So when I try #table(columns: my_counter) I get the expected error that content instead of int was found.
I tried #int(my_counter) to convert it to int but this did not work either.
How can I get a variable of type int from my context script?
You can’t, context is opaque. The intended way to do it is like this:
// this is now a function
#let my_counter() = {
let chapters = query(heading.where(level: 1))
let chap_len = chapters.len()
chap_len
}
// We invoke context so that we can create a table
// that depends on a context-dependent function result
#context {
table(columns: my_counter())
}
Now you can see that we have logical semantics - the whole table construction depends on the query and the location context, so the whole table has to be inside the context.
I was not aware of being able to use contextual functions like query outside of context, when used inside a function. This is (at least to me) something fundamental I learned from your answer.
I think I get the idea behind your beautifully simple solution, although I have to confess that I do no fully understand, why my_counter needs to be a function. My non-IT-background brain tries to explain this in the way that my_counterdoes not have an a priori value but rather calculates its value dependent of the context.