ketupia
Add or update function?
I find myself writing this code repeatedly. Is there a better way
if Status.exists?(entity) do
Status.update(entity, new_value)
else
Status.add(entity, new_value)
end
Most Liked
smathy
Ironically, :ets has only a single insert that either adds or updates (overwrites). As you can see in the sauce the main difference between add and update is essentially just a guard to prevent existing elements from being overwritten, or non-existing elements from being auto-created.
There’s no upsert operation, might be worth submitting a PR.
APB9785
As @smathy pointed out, :ets inserts generally allow overwrites, and this was originally how ECSx worked as well, with just a single add operation that covered both cases. The reason we separated into two functions, is because of component persistence. Take the following case:
HitPoints.add(player, 100, persist: true)
HitPoints.add(player, 95)
The first operation inserts a persistent HitPoints component with value 100
The second operation overwrites this with a non-persistent (default is false) HitPoints component with a value of 95.
What was the problem? If a user provides options to the component creation, they would have to remember those options and pass them to every update, forever. Forgetting to include the original options would overwrite with the defaults. We considered setting the options globally, but quickly found use-cases where a single component type (such as HitPoints) would be persisted for some entities, but non-persisted for others. And we want to keep the door open for future options to be added.
So the end result is that we need one function for the original creation of a component, where the options are set, and then another function for updating the component, where no options = keep the existing options.







