local uuidmgr = { fileversion = 0 } local uuidstorage = {} local storeheader = "c36HH" -- oops do local store = io.open("uuidstore.dat", "r") if store then if native.debug then lprint("DEBUG: Loading uuidstore.dat...") end pcall(function() local version, count = string.unpack("IH", store:read(6)) if native.debug then lprint(string.format("DEBUG: File version %u, count %u", version, count)) end if version > uuidmgr.fileversion then lprint("ERROR: Invalid version!") error("invalid version") end for i=1, count do local uuid, clen, ilen = storeheader:unpack(store:read(storeheader:packsize())) local cname, id = store:read(clen), store:read(ilen) uuidstorage[cname] = uuidstorage[cname] or {} uuidstorage[cname][id] = uuid if native.debug then lprint(string.format("DEBUG: Found %s:%s's UUID of %s", cname, id, uuid)) end end store:close() end) end end function uuidmgr.lookup(component, identifier) uuidstorage[component] = uuidstorage[component] or {} local uuid = uuidstorage[component][identifier] if not uuid then uuid = modules.random.uuid() if native.debug then lprint(string.format("DEBUG: Registed component of type %s with identifier %s as uuid %s", component, identifier, uuid)) end uuidstorage[component][identifier] = uuid uuidmgr.store() else if native.debug then lprint(string.format("DEBUG: Looked up component of type %s with identifier %s as uuid %s", component, identifier, uuid)) end end return uuid end function uuidmgr.store() local store = io.open("uuidstore.dat", "w") local saved_ids = {} for component, ids in pairs(uuidstorage) do for id, uuid in pairs(ids) do table.insert(saved_ids, {uuid=uuid, component=component, id=id}) end end if native.debug then lprint(string.format("DEBUG: Saving %d static UUIDs", #saved_ids)) end store:write(string.pack("IH", uuidmgr.fileversion, #saved_ids)) for i=1, #saved_ids do local uuid, component, id = saved_ids[i].uuid, saved_ids[i].component, saved_ids[i].id store:write(storeheader:pack(uuid, #component, #id),component,id) if native.debug then lprint(string.format("DEBUG: Saving %s:%s as %s", component, id, uuid)) end end store:close() end return uuidmgr