From 8c28cab79289df1ef35e3e8c15993dc67d487a89 Mon Sep 17 00:00:00 2001 From: Ukendio Date: Mon, 9 Sep 2024 03:22:55 +0200 Subject: [PATCH] Add tests for hooks cache --- test/hooks.luau | 47 +++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 47 insertions(+) create mode 100644 test/hooks.luau diff --git a/test/hooks.luau b/test/hooks.luau new file mode 100644 index 00000000..bebe4a10 --- /dev/null +++ b/test/hooks.luau @@ -0,0 +1,47 @@ +local jecs = require("@jecs") + +local function create_cache(hook) + local columns = setmetatable({}, { + __index = function(self, component) + local column = {} + self[component] = column + return column + end + }) + + return function(world, component, fn) + local column = columns[component] + table.insert(column, fn) + world:set(component, hook, function(entity, value) + for _, callback in column do + callback(entity, value) + end + end) + end +end + +local hooks = { + OnSet = create_cache(jecs.OnSet), + OnAdd = create_cache(jecs.OnAdd), + OnRemove = create_cache(jecs.OnRemove) +} + +local world = jecs.World.new() +local Position = world:component() +local order = "" +hooks.OnSet(world, Position, function(entity, value) + print("$1", entity, `({value.x}, {value.y}, {value.z})`) + order ..= "$1" +end) +hooks.OnSet(world, Position, function(entity, value) + print("$2", entity, `\{{value.x}, {value.y}, {value.z}}`) + order ..= "-$2" +end) + +world:set(world:entity(), Position, {x=1,y=0,z=1}) + +-- Output: +-- $1 270 (1, 0, 1) +-- $2 270 {1, 0, 1} + +assert(order == "$1".."-".."$2")