|
| 1 | +local jecs = require("@jecs") |
| 2 | + |
| 3 | +local function create_cache(hook) |
| 4 | + local columns = setmetatable({}, { |
| 5 | + __index = function(self, component) |
| 6 | + local column = {} |
| 7 | + self[component] = column |
| 8 | + return column |
| 9 | + end |
| 10 | + }) |
| 11 | + |
| 12 | + return function(world, component, fn) |
| 13 | + local column = columns[component] |
| 14 | + table.insert(column, fn) |
| 15 | + world:set(component, hook, function(entity, value) |
| 16 | + for _, callback in column do |
| 17 | + callback(entity, value) |
| 18 | + end |
| 19 | + end) |
| 20 | + end |
| 21 | +end |
| 22 | + |
| 23 | +local hooks = { |
| 24 | + OnSet = create_cache(jecs.OnSet), |
| 25 | + OnAdd = create_cache(jecs.OnAdd), |
| 26 | + OnRemove = create_cache(jecs.OnRemove) |
| 27 | +} |
| 28 | + |
| 29 | +local world = jecs.World.new() |
| 30 | +local Position = world:component() |
| 31 | +local order = "" |
| 32 | +hooks.OnSet(world, Position, function(entity, value) |
| 33 | + print("$1", entity, `({value.x}, {value.y}, {value.z})`) |
| 34 | + order ..= "$1" |
| 35 | +end) |
| 36 | +hooks.OnSet(world, Position, function(entity, value) |
| 37 | + print("$2", entity, `\{{value.x}, {value.y}, {value.z}}`) |
| 38 | + order ..= "-$2" |
| 39 | +end) |
| 40 | + |
| 41 | +world:set(world:entity(), Position, {x=1,y=0,z=1}) |
| 42 | + |
| 43 | +-- Output: |
| 44 | +-- $1 270 (1, 0, 1) |
| 45 | +-- $2 270 {1, 0, 1} |
| 46 | + |
| 47 | +assert(order == "$1".."-".."$2") |
0 commit comments