Add queryFirstWithTraits#229
Conversation
|
I added LMK if either of those are preferable to this and I'd be happy to change this PR to match. |
|
I forgot about this, my apologies. I can see what we are trying to avoid is this kind of pattern. const entity = world.queryFirst(Position, Name)
if (!entity) return // What if no entity exists?
const name = entity.get(Name)!
const position = entity.get(Position)!And while something this API looks ergonomic: const [entity, position, name] = world.readFirst(Position, Name)It starts to look a lot less ergonomic to me once we consider the what happens when the entity does not exist? // We are destructuring so all of the array members are no filled with `undefined`
const [entity, position, name] = world.readFirst(Position, Name)
// And we have to check before moving forward anwyays
if (!entity) returnSo it looks like what we save is all the get calls. But what if you could just batch get? const entity = world.queryFirst(Position, Name)
if (!entity) return
const [position, name] = entity.get(Position, Name)Now this looks equally ergonomic again. So, I am not convinced the kind of proposed API is actually helpful. It is probably have the strict boundary check be "does my entity exist?" and not "does my data exist?" |
|
What I'm mostly trying to avoid are the non-null assertions, or the requirement to check each trait individually. I like the |
|
Hmm, I don't think the const [entity, position, name] = world.readFirst(Position, Name) // All types are T | undefined
if (!entity) return
position!.x // This still requires an assertion or a check above with entitySo it looks like the same ergonomics to me with less API surface if you can batch get all values at once. Am I wrong? const entity = world.queryFirst(Position, Name)
if (!entity) return
const [position, name] = entity.get(Position, Name)The only way to avoid assertion is actually to make another change -- allow the |
|
The type Guarantees that all elements in the return tuple are either undefined or present. So checking the entity is enough for the type checker to know that the traits are all defined. There is a test to that effect in the PR as well. |
|
Ah hah, I see the vision now. I did not know you could do this! I am going to reconsider. |
This is mostly just a proof of concept - obviously doesn't make sense unless you're satisfied with the api @krispya