home · login to get plonkin'

lua ecs (WIP, UNTESTED)

@koldinium.bsky.plasmatrap.com · 14d ago · plaintext · 71 loc · raw · 0 comments

1-- ENTITY COMPONENT SYSTEM2-- Created by Koldinium3-- Licensed under 0BSD4local M = {}56-- Maintain one consistent global state across instances7_G.__kold_ecs = _G.__kold_ecs or {}8local globals = _G.__kold_ecs910globals.entities = globals.entities or 011globals.component_arrays = globals.component_arrays or {}12globals.components = globals.components or {}13globals.systems = globals.systems or {}141516function M.create_entity(components)17    local id = globals.entities + 118    for k,v in pairs(components) do19        globals.component_arrays[k][id] = globals.components[k](v)20    end21    return id22end2324function M.delete_entity(id)25    for _,v in pairs(globals.component_arrays) do26        v[id] = nil27    end28end2930function M.add_component_to_entity(entity, component_id, component_val)31    globals.component_arrays[component_id][entity] = globals.components[component_id](component_val)32end3334function M.remove_component_from_entity(entity, component_id)35    globals.component_arrays[component_id][entity] = nil36end3738function M.declare_system(query, system)39    table.insert(globals.systems, {query = query, system=system})40end4142function M.declare_component(component, initializer)43    globals.components[component] = initializer44end454647function M.run_systems()48    for _,system in pairs(globals.systems) do49        local first_component_id = system.query[1]50        for id, component in globals.component_arrays[first_component_id] do51            if #system.query == 1 then52                system.system({component})53            else54                local arg = {}55                for k,v in pairs(system.query) do56                    if component_arrays[v][id] then57                        table.insert(arg, component_arrays[v][id])58                    else59                        break60                    end61                end62                if #arg == #system.query then63                    system.system(arg)64                end65            end66        end67    end68end6970return M71

login to post a comment