How to use state to get a global access to some value?

Hi !

I’m new to typst so I’m a little bit lost, especially when it comes about context and location.

I’m trying to get a global access to some immutable state through all my document.

I’m creating some state.typ file with following code:

#let character = state("character", yaml("../builder/chars/Shrimp.yml"))

Then I’m trying to use it like so in another file of my document:

#import "../components/state.typ" :  /* getCharacter */ character
#character.get()

But I get an error:

can only be used when context is known

Hint: try wrapping this in a `context` expression

I tried to make it work with context, but I think I’m just confused about how context work.

Hello and welcome to the forum!

Fixing the issue you are experiencing should be an easy fix; Just replace

#character.get()

with

#context character.get()

To understand more about context expressions, I recommend this answer by laurmaedje.

1 Like

Some notes:

  • Since state is a global thing, you don’t have to import it, unless you don’t want to write the name of the state (i.e., #context state("character").get()).
  • When speaking about a custom state() or variable, there is nothing immutable generally speaking, only some “built-in” things are immutable.
  • When writing a code block, it’s better to add the language (or its shorthand) in use to trigger correct syntax highlighting, i.e.:
    ```typ
    #let character = state("character", yaml("../builder/chars/Shrimp.yml"))
    ```
    
  • docs: State Type – Typst Documentation, Context – Typst Documentation + there is a new change coming:
1 Like