Define a named value only once
defonce
[name (symbol)]
Allows you assign the result of some code to a name with the property that the code will only execute once therefore stopping re-definitions. This is useful for defining values that you use in your compositions but you don't want to reset every time you press run. You may force the block to execute again regardless of whether or not it has executed once already by using the override option (see examples).
Introduced in v2.0.0
|
defonce :foo do sleep 1 puts "hello" 10 end # Call foo on its own puts foo # Try it again: puts foo defonce :foo do puts "you can't redefine me" 15 end puts foo # You can use foo anywhere you would use normal code. # For example, in a block: 3.times do play foo end |
# Define a new function called foo # Sleep for a second in the function definition # Print hello # Return a value of 10 # The run sleeps for a second and prints "hello" before returning 10 # This time the run doesn't sleep or print anything out. However, 10 is still returned. # Try redefining foo # We still don't see any printing or sleeping, and the result is still 10 # play 10 |
|
defonce :bar do 50 end play bar defonce :bar do 70 end play bar defonce :bar, override: true do 80 end play bar |
# plays 50 # This redefinition doesn't work due to the behaviour of defonce # Still plays 50 # Force definition to take place with override option # plays 80 |