matter-ecs / matter

A modern ECS library for Roblox
https://matter-ecs.github.io/matter/
MIT License
65 stars 12 forks source link

searching for components with specific data #123

Open fl215 opened 1 day ago

fl215 commented 1 day ago

Problem

there is some boilerplate in this code that I don't think people should have to always be writing and there could be mistakes done, like writing return instead of continue

for id, tool in world:query(Tool) do
  if not(tool.type == "weapon")then continue end
end

Proposed solution

fixing this solution by introducing the where method

local needs = {
  [Tool] = {type = "weapon"}
}

for id, tool in world:query(Tool):where({ [Tool] = {type = "weapon"} }) do
  -- code without that boilerplate
end

reading it also pretty intuitive: query Tool where Tool's type is weapon

some more useful examples:

for id, tool, model, player in world:query(Tool, Model, Player):where({
  [Tool] = {type = "weapon"},
  [Player] = {name = "Loduha", id = 23},
}) do
  -- query tool, model and player where the tool's type is weapon and the player's name and id are Loduha and 23 respectively
end

there can also be functions

local acceptedToolTypes = {
  ["weapon"] = true,
  ["potion"] = true,
}

local needs = {
  [Tool] = function(tool) return acceptedToolTypes[tool.type] end
}

for id, tool, model, player in world:query(Tool, Model, Player):where(needs) do
  -- query the tool where the tool's type is either weapon or potion
end
fl215 commented 1 day ago

additional information: you could rename where to whereAll and add a whereAny where any of the conditions must pass

LastTalon commented 11 hours ago

This seems like a decent idea, but needs more consideration for the precise API and how it fits into our future plans for queries and relationships.

jackTabsCode commented 10 hours ago

I would also note that in this specific example, you could benefit from just giving your entities with the Tool component additional components like Weapon and Potion. You'd also get increased performance out of Matter by doing so.

fl215 commented 10 hours ago

I would also note that in this specific example, you could benefit from just giving your entities with the Tool component additional components like Weapon and Potion. You'd also get increased performance out of Matter by doing so.

you are right, I should have thought more about the examples, these examples may not seem very great but in more complex game structures it might pose a benefit.