summaryrefslogtreecommitdiff
path: root/honey/ecs.lua
blob: b4def84cd1480d0e07249e6985a076aad8d22546 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
local module = {}
setmetatable(module, {__index=_G})
setfenv(1, module)


--===== Components =====--

Component = {}

function Component.newFactory(name, params, serialize)
	local metatable = {}
	metatable.__tostring = serialize or Component.serialize
	metatable.__newindex = function(tbl, index, value)
		if params[index] ~= nil then
			tbl[index] = value
		else
			error(string.format("%q is not a valid key for a component of type %q", index, name))
		end
	end
	return function(tbl)
		local tbl = tbl or {}
		local self = { __type=name }
		for k, v in pairs(params) do
			self[k] = v
		end
		setmetatable(self, metatable)
		for k, v in pairs(tbl) do
			self[k] = v
		end
		return self
	end
end


function Component.serialize(self)
	local str = "{"
	for k, v in pairs(self) do
		if type(v) == "string" then
			str = str .. string.format("%s=%q,", k, v)
		else
			str = str .. string.format("%s=%s,", k, tostring(v))
		end
	end
	str = string.sub(str, 1, -2) .. "}"
	return str
end

return module