Skip to content

Instantly share code, notes, and snippets.

@pcornier
Last active April 8, 2020 15:37
Show Gist options
  • Save pcornier/562efab321ac69cc4a87c6f4517b770c to your computer and use it in GitHub Desktop.
Save pcornier/562efab321ac69cc4a87c6f4517b770c to your computer and use it in GitHub Desktop.
very basic Node tree system
const Node = function(...nodes) {
let children = nodes
let node = {
addChild: n => children.push(n),
register: (name, callback) => {
this[name] = callback
return node
},
call: (name, ...args) => {
if (this[name]) this[name](args)
children.forEach(c => c.call(name, args))
},
}
return node
}
let root = new Node(
new Node(
new Node().register('update', () => console.log('with a shield')),
new Node().register('update', () => console.log('and a helmet'))
).register('update', () => console.log('I have an armor')),
new Node().register('update', () => console.log('And a sword !!'))
)
.call('update')
@pcornier
Copy link
Author

pcornier commented Apr 8, 2020

LUA version

function Node()
  local node = {}
  local children = {}
  function node.add(n)
    n.parent = node
    table.insert(children, n)
  end
  function node.register(name, cb)
    node[name] = cb
    return node
  end
  function node.call(name, ...)
    if node[name] then node[name](node, ...) end
    for _,n in pairs(children) do
      n.call(name, ...)
    end
  end
  return node
end

function render(n)
  local x = n.x
  local y = n.y
  if n.parent then
    x = x + n.parent.x or 0
    y = y + n.parent.y or 0
  end
  print('rendering ' .. n.name .. ' at pos ' .. x .. ',' .. y)
end

head = Node()
head.name = 'head'
head.x = 1
head.y = -5
head.register('render', render)

body = Node()
body.name = 'body'
body.x = 0
body.y = 0
body.register('render', render)

body.add(head)
body.call('render')
-- rendering body at pos 0,0
-- rendering head at pos 1,-5
body.x = 10
body.y = 10
body.call('render')
-- rendering body at pos 10,10
-- rendering head at pos 11,5

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment