Ownership
Instances are owned by whatever scope they get assigned into. If their scope ends, they also end.
This instance doesn't get stored in memory because it isn't assigned anywhere:
new [score = 0]
This instance gets stored in memory in the global scope:
let player = new [score = 0]
This player
instance gets stored in the function's scope, and then is lost when the function ends:
let createPlayer = [] -> {
let player = new [score = 0]
}
Transfer
You can transfer ownership of an instance by re-assigning it to something else.
This player
instance gets stored in the global scope because it gets assigned into the globally-scoped players
instance.
let players = new [?]
let createPlayer = [n] -> {
let player = new [score = 0]
players.(n) = player
}
This also works with returning. This player
instance continues to exist after the function call because it gets assigned into the globally-scoped playerOne
.
let makePlayer = [] => {
let player = new [score = 0]
return player
}
let playerOne = makePlayer()
Reference
You can assign a reference of an instance with the @
character. This doesn't transfer ownership.
This stores a reference of the player
instance inside playerOne
. The true ownership of the instance is stored in players
.
let players = new [?]
let createPlayer = [n] => {
let player = new [score = 0]
players.(n) = player
return @player
}
let playerOne = createPlayer(1)
Last updated
Was this helpful?