makspll / bevy_mod_scripting

Bevy Scripting Plugin
Apache License 2.0
411 stars 31 forks source link

Dynamic Queries #118

Closed Mistrustfully closed 6 months ago

Mistrustfully commented 6 months ago

Fixes #20 Adds API methods for dynamic queries, using the new QueryBuilder added in Bevy 0.13. Both Lua and Rhai have implementations as well as types for Teal.

Lua:

local ComponentOne = world:get_type_by_name("ComponentOne")
local ComponentTwo = world:get_type_by_name("ComponentTwo")
local ComponentThree = world:get_type_by_name("ComponentThree")
local ComponentFour = world:get_type_by_name("ComponentFour")

-- `world:query` accepts any number of `LuaTypeRegistration`
-- returns a `LuaQueryBuilder` which can be used to further filter the query with the `:with` and `:without` methods
-- `LuaQueryBuilder` has an `:iter` method which resolves the query and returns an iterator over the entities and components

for entity, componentOne, componentTwo in world:query(ComponentOne, ComponentTwo):with(ComponentThree):without(ComponentFour):iter() do
    print(entity, componentOne, componentTwo)
end

Rhai:

let component_one = world.get_type_by_name("ComponentOne");
let component_two = world.get_type_by_name("ComponentTwo");
let component_three = world.get_type_by_name("ComponentThree");
let component_four = world.get_type_by_name("ComponentFour");

// `world.query` accepts an array of `ScriptTypeRegistration`
// returns a `ScriptQueryBuilder` which can be used to further filter the query with the `.with` and `.without` methods
// Iterating over `ScriptQueryBuilder` will resolve the query

for results in world.query([ ComponentOne, ComponentTwo ]).with([ ComponentThree ]).without([ ComponentFour ]) {
    // `results` is an object map, keys being the type name of the component, and the values being the entities' component
    // `results` also has a `Entity` key, being the entity the query matched against
    print(results.Entity);
    print(results.ComponentOne);
    print(results.ComponentTwo);
}
makspll commented 6 months ago

Very solid work, Much appreciated! It's also very nice that it mostly fit without much trouble into the existing framework!