References
Basic Usage
Sparkle by default deep copies values when they are assigned to a variable or passed to a function.
let painter be object with
name as "Picasso", and
age as 60
let picasso be painterIn the example above, we are assigning painter to picasso, but since
it's a copy, any changes to picasso will not affect painter.
update picasso's age to 91
print painter's age # <-- still 60To create a reference to a variable, object property, or list element, use let ... be ... by reference when declaring a new variable.
let picasso be painter by reference
update picasso's age to 91
print painter's age # <-- now 91Limitations
Important to note that by reference does not work on update ... to ..., object properties, or list elements.
let best_color be "red"
let my_color be "blue"
update my_color to best_color by reference # <-- not allowed
let best_name be "Alice"
let alice be object with
name as best_name by reference, and # <-- not allowed
age as 24
let best_number be 2
let lst be list with 1, best_number by reference, and 3 # <-- not allowedLists and Objects
References can be made to list elements.
let lst be list with 1, 2, and 3
let first be lst at 0 by reference
update first to first plus 1
print lst # list with 2, 2, and 3And object properties.
let pet be object with
name as "Fido", and
age as 5
let dog_age be pet's age by reference
update dog_age to 10
print pet's age # 10References to References
References can be made to references, and it is equivalent to making a reference to the original value. All references to the same value will update synchronously.
let a be 1
let b be a by reference
let c be b by reference
update c to c plus 1
print a # 2
print b # 2
print c # 2When you assign a reference to another variable without using by reference, it
will perform a copy of the original value.
let pet be "Fido" # original value
let dog be pet by reference # reference to original value
let friend be dog # copy of original valueIn Function Arguments
Function arguments can be defined as references using the by reference keyword.
let swap be function with a by reference, and b by reference as
let temp be a
update a to b
update b to tempThe by reference keyword is then required when calling the function.
let a be 1
let b be 2
call swap with a by reference, and b by reference
print a # 2
print b # 1This is a two-way agreement, if there is a mismatch between the usage of by reference in the function definition and call, a runtime error will be thrown.
As a return value
It is possible to get a reference as a return value using return ... by reference and then assign it to a variable using let ... be ... by reference.
let numbers be list with 1, 2, and 3
let get_first be function as
return numbers at 0 by reference
let first be call get_first by reference
update first to first plus 1
print numbers # list with 2, 2, and 3If the second usage of by reference is missing, it will instead assign a copy of the
value.