Skip to content

Commit

Permalink
Allow different datatypes in the same component
Browse files Browse the repository at this point in the history
  • Loading branch information
memorycode committed Nov 16, 2024
1 parent cb5c81c commit a777bd7
Show file tree
Hide file tree
Showing 3 changed files with 14 additions and 12 deletions.
17 changes: 7 additions & 10 deletions lib/Component.luau
Original file line number Diff line number Diff line change
Expand Up @@ -55,21 +55,18 @@ local function new(name: string, defaultData)
ComponentInstance.__index = ComponentInstance

function ComponentInstance.new(data)
local mt = getmetatable(ComponentInstance :: any)
if typeof(data) == "table" then
data = data or {}
data = if data == nil then defaultData or {} else data

local component = getmetatable(ComponentInstance :: any)
if typeof(data) == "table" then
if defaultData then
data = merge(defaultData, data)
end

mt[PRIMITIVE_MARKER] = false
return setmetatable(table.freeze(data), ComponentInstance)
return table.freeze(setmetatable(data, ComponentInstance))
else
data = data or defaultData

mt[PRIMITIVE_MARKER] = true
return setmetatable({ data }, ComponentInstance)
component[PRIMITIVE_MARKER] = true
return table.freeze(setmetatable({ data = data, [PRIMITIVE_MARKER] = true }, ComponentInstance))
end
end

Expand Down Expand Up @@ -184,7 +181,7 @@ local function assertComponentArgsProvided(...)
end

local function isPrimitive(componentInstance)
return getmetatable(componentInstance)[PRIMITIVE_MARKER] == true
return componentInstance[PRIMITIVE_MARKER] ~= nil
end

return {
Expand Down
5 changes: 3 additions & 2 deletions lib/World.luau
Original file line number Diff line number Diff line change
Expand Up @@ -271,7 +271,7 @@ local function executeInsert(world: World, insertCommand: InsertCommand)
local component = getmetatable(componentInstance)
local componentId = #component
local componentIds = table.clone(oldArchetype.componentIds)
local isPrimitive = Component.isPrimitive(component)
local isPrimitive = Component.isPrimitive(componentInstance)

local archetype: Archetype
local entityIndex: number
Expand All @@ -291,8 +291,9 @@ local function executeInsert(world: World, insertCommand: InsertCommand)
end

archetype.fields[archetype.idToIndex[componentId]][entityIndex] = if isPrimitive
then componentInstance[1]
then componentInstance.data
else componentInstance

world:_trackChanged(component, entityId, oldComponentInstance, componentInstance)

oldArchetype = archetype
Expand Down
4 changes: 4 additions & 0 deletions lib/World.spec.luau
Original file line number Diff line number Diff line change
Expand Up @@ -149,6 +149,10 @@ return function()
local B = component()

world:spawn(A("hello"))
world:spawn(A(1))
world:spawn(A({ whats_good = true }))
world:spawn(A())
world:spawn(A("test"))

for id, a in world:query(A) do
print(id, a)
Expand Down

0 comments on commit a777bd7

Please sign in to comment.