Skip to content

Instantly share code, notes, and snippets.

@rcolinray
Created September 4, 2018 02:52
Show Gist options
  • Save rcolinray/9ca7306cf10346c6ac3fc6185d50ed76 to your computer and use it in GitHub Desktop.
Save rcolinray/9ca7306cf10346c6ac3fc6185d50ed76 to your computer and use it in GitHub Desktop.
Entity-component helpers for Pico-8
------------
-- object --
------------
-- base prototype
object={}
function object:new(o)
o=o or {}
setmetatable(o,self)
self.__index=self
return o
end
------------
-- entity --
------------
-- container for components
entity=object:new()
-- construct a new entity instance
function make_entity()
return entity:new{
children={},
to_update={},
to_draw={}
}
end
-- add a component instance
function entity:attach(c)
self.children[c.id]=c
c.parent=self
if (c.update) add(self.to_update,c.id)
if (c.draw) add(self.to_draw,c.id)
end
-- remove a component instance
function entity:detach(c)
self.children[c.id]=nil
c.parent=nil
if (c.update) del(self.to_update,c.id)
if (c.draw) del(self.to_draw,c.id)
end
-- retrieve a component instance
-- c is a component prototype
function entity:get(c)
return self.children[c.id]
end
-- update all child components
function entity:update()
for _,i in pairs(self.to_update) do
self.children[i]:update()
end
end
-- draw all child components
function entity:draw()
for _,i in pairs(self.to_draw) do
self.children[i]:draw()
end
end
---------------
-- component --
---------------
-- base component prototype
component=object:new{
id=nil
}
-- construct a new component instance
function make_component()
return component:new{
parent=nil,
}
end
-- get another component on the same entity
function component:get(c)
return self.parent:get(c)
end
------------
-- pico-8 --
------------
function _init()
world={}
end
function _update()
for _,e in pairs(world) do
e:update()
end
end
function _draw()
cls()
for _,e in pairs(world) do
e:draw()
end
print_perf()
end
-- print performance stats
function print_perf()
print("mem:"..stat(0))
print("cpu:"..stat(1))
print("sys:"..stat(2))
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment