The option
type can contain one value or can be empty.
In the following example, MaybeANumber
is an optional integer ?int
that contains no value. A new value for MaybeANumber
is then set to 42
.
var MaybeANumber : ?int = false # unset optional value
set MaybeANumber := option{42} # assigned the value 42
|
Creating an option: You can initialize an option with one of the following:
Specify the type by adding |
|
Accessing an element in an option: Use the query operator ? with the option, such as MaybeANumber? . Accessing the value stored in an option is a failable expression because there might not be a value in the option, and so must be used in a failure context. |
The following is an example of using an option type to save a reference to a spawned player and, when a player is spawned, to have the trigger device react:
my_device := class<concrete>(creative_device):
var SavedPlayer : ?player = false # unset optional value
@editable
PlayerSpawn : player_spawner_device = player_spawner_device{}
@editable
Trigger : trigger_device = trigger_device{}
OnBegin<override>() : void =
PlayerSpawn.PlayerSpawnedEvent.Subscribe(OnPlayerSpawned)
OnPlayerSpawned(Player : player) : void =
set SavedPlayer = option{Player}
if (TriggerPlayer := SavedPlayer?):
Trigger.Trigger(TriggerPlayer)
Persistable Type
An option is persistable if its value is persistable, which means that you can use them in your module-scoped weak_map
variables and have their values persist across game sessions. For more details on persistence in Verse, check out Using Persistable Data in Verse.