2024-08-03 03:48:48 +00:00
|
|
|
local jecs = require("@jecs")
|
2025-08-29 15:13:13 +00:00
|
|
|
local world = jecs.world()
|
2024-08-03 03:48:48 +00:00
|
|
|
|
2025-08-29 15:13:13 +00:00
|
|
|
local Position = world:component() :: jecs.Id<vector>
|
2024-08-03 03:48:48 +00:00
|
|
|
local Walking = world:component()
|
2025-08-29 15:13:13 +00:00
|
|
|
local Name = world:component() :: jecs.Id<string>
|
|
|
|
|
|
|
|
local function name(e: jecs.Entity): string
|
|
|
|
return assert(world:get(e, Name))
|
|
|
|
end
|
2024-08-03 03:48:48 +00:00
|
|
|
|
|
|
|
-- Create an entity with name Bob
|
|
|
|
local bob = world:entity()
|
|
|
|
|
|
|
|
-- The set operation finds or creates a component, and sets it.
|
2025-08-29 15:13:13 +00:00
|
|
|
world:set(bob, Position, vector.create(10, 20, 30))
|
2024-08-03 03:48:48 +00:00
|
|
|
-- Name the entity Bob
|
|
|
|
world:set(bob, Name, "Bob")
|
|
|
|
-- The add operation adds a component without setting a value. This is
|
|
|
|
-- useful for tags, or when adding a component with its default value.
|
|
|
|
world:add(bob, Walking)
|
|
|
|
|
|
|
|
-- Get the value for the Position component
|
|
|
|
local pos = world:get(bob, Position)
|
2025-08-29 15:13:13 +00:00
|
|
|
assert(pos)
|
|
|
|
print(`\{{pos.x}, {pos.y}, {pos.z}\}`)
|
2024-08-03 03:48:48 +00:00
|
|
|
|
|
|
|
-- Overwrite the value of the Position component
|
2025-08-29 15:13:13 +00:00
|
|
|
world:set(bob, Position, vector.create(40, 50, 60))
|
2024-08-03 03:48:48 +00:00
|
|
|
|
|
|
|
local alice = world:entity()
|
|
|
|
-- Create another named entity
|
|
|
|
world:set(alice, Name, "Alice")
|
2025-08-29 15:13:13 +00:00
|
|
|
world:set(alice, Position, vector.create(10, 20, 30))
|
2024-08-03 03:48:48 +00:00
|
|
|
world:add(alice, Walking)
|
|
|
|
|
|
|
|
-- Remove tag
|
|
|
|
world:remove(alice, Walking)
|
|
|
|
|
|
|
|
-- Iterate all entities with Position
|
|
|
|
for entity, p in world:query(Position) do
|
2025-08-29 15:13:13 +00:00
|
|
|
print(`{name(entity)}: \{{p.x}, {p.y}, {p.z}\}`)
|
2024-08-03 03:48:48 +00:00
|
|
|
end
|
|
|
|
|
|
|
|
-- Output:
|
|
|
|
-- {10, 20, 30}
|
|
|
|
-- Alice: {10, 20, 30}
|
|
|
|
-- Bob: {40, 50, 60}
|