How to check if a variable exists?

Hey :wave: ,

I am trying to check if a variable exists - but as far as i could imagine doing it, i don’t see a way to do it.

Say i’d like to detect if “a” is being defined declared - i thought of using something like if a ... which of course fails.

So how actually check if an variable exists?

You can check it yourself, e.g.

#let a

a is declared but not defined. The representation of a is

repr(a) // none

none. So checking for none should be sufficient:

#{a == none} // true

Since if requires a boolean condition to be met, we can check:

#if a == none [Yes] else [No] // Yes

On the other hand. a is not none when it is defined:

#let a = 5 // declared and defined
#{a == none} // false
2 Likes

Dear @gpr - thank you very much for your expressive example! I am so sorry i didn’t make clear that i actually try to detect if a variable is already declared (not defined). :bowing_man:

Sorry, maybe I misunderstood something, but this is how you would check whether a variable is defined:

a != none // checks whether a is defined

Evaluates to true if a is defined, e.g.

#{if a != none [a is defined here continue...]}

As far as I know there is no syntax like if a

1 Like

This will error if a is not in scope. I think what @Florian is trying to do is to check whether it is in scope.

It’s not possible to check this (at least I’m not aware of any way). There is a small exception: If the bindings come from an imported module, you can convert the whole module to a dictionary with the dictionary constructor and check whether it’s contained. For the standard library definitions that module would be std. That lets you solve a subproblem of your question.

All that said: Even if there was a way, it would be quite unorthodox to perform such a check. What are you actually trying to achieve? Maybe there is a better way.

1 Like

Thanks a lot @gpr and @laurmaedje.

I am recently thinking of and writing modules for different use cases.

And of course i am aware of a) the immutable nature of the processing pipeline diverging to the best result and b) i usually would recommend to put a lot of the data preparing to a preprocessing outside of Typst.

But i experiment a lot with different ways to use Typst as the interface for more or less complex tasks which leads to a annoyingly enjoyable experience creating user interfaces in the Typst scripting language.

In that regard i thought about using state variables behind the scenes, to allow modules to implicitly use the state of other modules.

Don’t get me wrong i think that’s a bit of an antipattern since it could raise issues but in terms of exploring what one could achieve i was interested to find out if it’s possible.