Advertisement
Guest User

instance ids

a guest
Feb 23rd, 2020
115
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Lua 2.05 KB | None | 0 0
  1. --[[ DOCUMENTATION
  2.  
  3. = module(instance) [instance]
  4.     --> existing instance id if it exists, or new instance id
  5.  
  6. = module.new(instance) [instance]
  7.     --> returns a new custom instance object or an existing one if one exists
  8.         ~ .Unassociate() --> unassociate the tag with the instance
  9.         ~ .ID --> get the instance's id
  10.    
  11. = module.GetInstanceByID(id) [string]
  12.     --> get an instance by id. errors if id doesn't exist.
  13.  
  14. = module.UnregisterInstance(instance) [instance]
  15.     --> unassociate a tag with an instance.
  16.    
  17. = module.UnregisterID(id) [string]
  18.     --> unassociate a tag with an instance
  19. ]]
  20.  
  21.  
  22. local HTTPService = game:GetService('HttpService')
  23.  
  24. local module = {}
  25. module.__index = module
  26.  
  27. local registeredInstances = {}
  28.  
  29. setmetatable(module, {
  30.     __call = function(class, instance)
  31.         return class.new(instance).ID
  32.     end,
  33. })
  34.  
  35. function module.new(instance)
  36.     if registeredInstances[instance] then
  37.         return registeredInstances[instance]
  38.     end
  39.    
  40.     local self = setmetatable({}, module)
  41.     self:create(instance)
  42.     return self
  43. end
  44.  
  45. function module:create(instance)
  46.     self.ID = HTTPService:GenerateGUID(false)
  47.     registeredInstances[instance] = self
  48.    
  49.     function self.Unassociate()
  50.         registeredInstances[instance] = nil
  51.     end
  52.    
  53.     instance.AncestryChanged:Connect(function()
  54.         if not instance:IsDescendantOf(game) or not instance:IsDescendantOf(nil) then
  55.             module.UnregisterInstance(instance)
  56.         end
  57.     end)
  58. end
  59.  
  60. function module.GetInstanceByID(ID)
  61.     for instance, object in pairs(registeredInstances) do
  62.         if object.ID == ID then
  63.             return instance
  64.         end
  65.     end
  66.     return error('No instance with id: ', ID)
  67. end
  68.  
  69. function module.UnregisterInstance(instance)
  70.     if registeredInstances[instance] then
  71.         registeredInstances[instance] = nil
  72.         return
  73.     end
  74.     return error('Instance doesn\'t exist: ', tostring(instance))
  75. end
  76.  
  77. function module.UnregisterID(ID)
  78.     for instance, object in pairs(registeredInstances) do
  79.         if object.ID == ID then
  80.             registeredInstances[instance] = nil
  81.             return
  82.         end
  83.     end
  84.     return error('ID doesn\'t exist: ', ID)
  85. end
  86.  
  87. return module
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement