Skip to content

Instantly share code, notes, and snippets.

@RuizuKun-Dev
Last active January 27, 2023 04:17
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save RuizuKun-Dev/768981cc6d68f996a041a4fa1761ea02 to your computer and use it in GitHub Desktop.
Save RuizuKun-Dev/768981cc6d68f996a041a4fa1761ea02 to your computer and use it in GitHub Desktop.
--| LICENSE: https://gist.github.com/RuizuKun-Dev/768981cc6d68f996a041a4fa1761ea02#file-license-txt
local ReplicatedStorage = game:GetService("ReplicatedStorage")
local Configurations = ReplicatedStorage.Shared:FindFirstChild("Configurations")
and require(ReplicatedStorage.Shared.Configurations)
local Utilities = ReplicatedStorage.Utilities
local instanceUtil = require(Utilities.instanceUtil)
local JSON = require(Utilities.JSON)
local Promise = require(Utilities.Packages.Promise)
local t = require(Utilities.Packages.t) -- github.com/osyrisrblx/t
local tagUtil = require(Utilities.tagUtil)
local Codec = require(script.Codec)
local RunService = game:GetService("RunService")
local isRunning = RunService:IsRunning()
export type attributeUtil = {
ClearAllAttributes: (instance: Instance) -> void,
FindFirstChildWithAttribute: (parent: Instance, attribute: string, recursive: boolean?) -> Instance?,
Get: (instance: Instance, attribute: string) -> (any),
GetAttributes: (instance: Instance) -> (Dictionary),
GetChildrenWithAttribute: (Instance, string) -> Array<Instance>,
GetDescendantsWithAttribute: (Instance, string) -> Array<Instance>,
GetChangedSignal: (
instance: Instance,
attribute: string,
callback: (value: any) -> void
) -> RBXScriptConnection,
IsSpecialType: (value: any) -> (boolean),
IsSupportedType: (value: any) -> (boolean),
Set: (instance: Instance, attribute: string, value: any) -> void,
SetAttributes: (instance: Instance, attributes: { [string]: any }) -> void,
WaitForChildWithAttribute: (parent: Instance, attribute: string, timeOut: number?) -> Instance?,
WaitUntilAttributeIs: (instance: Instance, attribute: string, desiredValue: any?) -> Promise,
}
local attributeUtil = {
Attributes = Configurations and Configurations.ATTRIBUTES or {},
}
local SUPPORTED_TYPES: SUPPORTED_TYPES = require(script.SUPPORTED_TYPES)
local SPECIAL_TYPES: SPECIAL_TYPES = require(script.SPECIAL_TYPES)
function attributeUtil.IsSupportedType(value: any): boolean
return SUPPORTED_TYPES[typeof(value)]
end
function attributeUtil.IsSpecialType(value: any): boolean
return SPECIAL_TYPES[typeof(value)]
end
function attributeUtil.ClearAllAttributes(instance: Instance)
assert(t.Instance(instance))
for attribute: string, _ in pairs(attributeUtil.GetAttributes(instance)) do
if attribute ~= "GUID" then
attributeUtil.Set(instance, attribute, nil)
end
end
end
local FindFirstChildWithAttribute_Check = t.tuple(t.Instance, t.string, t.optional(t.boolean))
function attributeUtil.FindFirstChildWithAttribute(
parent: Instance,
attribute: string,
recursive: boolean?
): Instance | nil
assert(FindFirstChildWithAttribute_Check(parent, attribute, recursive))
if recursive then
for _, descendant: Instance in ipairs(parent:GetDescendants()) do
if attributeUtil.Get(descendant, attribute) then
return descendant
end
end
else
for _, child: Instance in ipairs(parent:GetChildren()) do
if attributeUtil.Get(child, attribute) then
return child
end
end
end
return nil
end
local InstanceAndString_Check = t.tuple(t.Instance, t.string)
function attributeUtil.Get(instance: Instance, attribute: string): any
assert(InstanceAndString_Check(instance, attribute))
local value = instance:GetAttribute(attribute)
return Codec.Decode(value) or value
end
function attributeUtil.GetAttributes(instance: Instance): Dictionary
assert(t.Instance(instance))
local attributes = instance:GetAttributes()
for attribute: string, value: any in pairs(attributes) do
attributes[attribute] = Codec.Decode(value) or value
end
return attributes
end
function attributeUtil.GetChildrenWithAttribute(parent: Instance, attribute: string): Array
assert(InstanceAndString_Check(parent, attribute))
local ChildrenWithAttribute = {}
for _, child: Instance in ipairs(parent:GetChildren()) do
if attributeUtil.Get(child, attribute) ~= nil then
table.insert(ChildrenWithAttribute, child)
end
end
return ChildrenWithAttribute
end
function attributeUtil.GetDescendantsWithAttribute(ancestor: Instance, attribute: string): Array
assert(InstanceAndString_Check(ancestor, attribute))
local DescendantsWithAttribute = {}
for _, descendant: Instance in ipairs(ancestor:GetDescendants()) do
if attributeUtil.Get(descendant, attribute) ~= nil then
table.insert(DescendantsWithAttribute, descendant)
end
end
return DescendantsWithAttribute
end
local SetAttribute_Check = t.tuple(t.Instance, t.union(t.string, t.integer), t.optional(t.any))
function attributeUtil.Set(instance: Instance, attribute: string, value: any)
assert(SetAttribute_Check(instance, attribute, value))
-- attribute = string.gsub(tostring(attribute):gsub("%f[%w]%l", string.upper), "[^%w_]+", "")
if attributeUtil.IsSupportedType(value) then
instance:SetAttribute(attribute, value)
elseif attributeUtil.IsSpecialType(value) then
instance:SetAttribute(attribute, Codec.Encode(value))
end
end
function attributeUtil.Remove(instance: Instance, attribute: string)
assert(InstanceAndString_Check(instance, attribute))
instance:SetAttribute(attribute, nil)
end
local SetAttributes_Check = t.tuple(t.Instance, t.table)
function attributeUtil.SetAttributes(instance: Instance, attributes: Dictionary)
assert(SetAttributes_Check(instance, attributes))
for attribute: string, value: any in pairs(attributes) do
attributeUtil.Set(instance, attribute, value)
end
end
local doForAttributeChanged_Check = t.tuple(t.Instance, t.string, t.callback, t.optional(t.boolean))
function attributeUtil.doForAttributeChanged(
instance: Instance,
attribute: string,
callback: (value: any) -> void,
expectNonNil: boolean?
): RBXScriptConnection
assert(doForAttributeChanged_Check(instance, attribute, callback, expectNonNil))
if expectNonNil and attributeUtil.Get(instance, attribute) == nil then
Promise.fromEvent(instance:GetAttributeChangedSignal(attribute), function()
return attributeUtil.Get(instance, attribute) ~= nil
end):andThen(function()
callback(attributeUtil.Get(instance, attribute))
end)
else
task.spawn(callback, attributeUtil.Get(instance, attribute))
end
return instance:GetAttributeChangedSignal(attribute):Connect(function()
callback(attributeUtil.Get(instance, attribute))
end)
end
local doForAttributeChanges_Check = t.tuple(t.Instance, t.callback)
function attributeUtil.doForAttributeChanges(instance: Instance, callback: (value: any) -> void): RBXScriptConnection
assert(doForAttributeChanges_Check(instance, callback))
return instance.AttributeChanged:Connect(function(attribute: string)
callback(attribute, attributeUtil.Get(instance, attribute))
end)
end
local WaitForChildWithAttribute_Check = t.tuple(t.Instance, t.string, t.optional(t.number))
function attributeUtil.waitForChildWithAttribute(parent: Instance, attribute: string, timeOut: number?): Instance | nil
assert(WaitForChildWithAttribute_Check(parent, attribute, timeOut))
local START_TIME = os.clock()
local YIELD_UNTIL = (timeOut and timeOut + START_TIME or math.huge)
local function yieldTooLongWarning()
local CURRENT_TIME = os.clock()
if CURRENT_TIME - START_TIME >= 5 then
warn("Infinite yield possible on WaitForChildWithAttribute:", parent.Name, attribute)
yieldTooLongWarning = nil
end
end
local CURRENT_TIME = os.clock()
while YIELD_UNTIL >= CURRENT_TIME do
for _, child: Instance in ipairs(parent:GetChildren()) do
if attributeUtil.Get(child, attribute) then
return child
end
end
if yieldTooLongWarning then
yieldTooLongWarning()
end
task.wait()
CURRENT_TIME = os.clock()
end
return nil
end
local YieldAttribute_Check = t.tuple(t.Instance, t.union(t.string, t.integer), t.optional(t.any))
function attributeUtil.waitUntilAttributeIs(instance: Instance, attribute: string, desiredValue: any?): Promise
assert(YieldAttribute_Check(instance, attribute, desiredValue))
if attributeUtil.Get(instance, attribute) == desiredValue then
return Promise.resolve(desiredValue)
end
local promise = Promise.fromEvent(instance:GetAttributeChangedSignal(attribute), function()
local currentValue = attributeUtil.Get(instance, attribute)
return currentValue == desiredValue
end)
local connection
connection = instance.Destroying:Connect(function()
promise:cancel()
end)
promise:finally(function()
connection:Disconnect()
end)
return promise:andThenReturn(desiredValue)
end
local Display_Check = t.tuple(t.Instance, t.table)
function attributeUtil.Display(instance: Instance, dictionary: Dictionary)
assert(Display_Check(instance, dictionary))
for attribute: string, value: any in pairs(JSON.Filter(dictionary, "Display")) do
if typeof(attribute) == "number" or typeof(attribute) == "string" then
if typeof(value) == "table" then
local configuration = instance:FindFirstChild(attribute) or Instance.new("Folder")
configuration.Name = attribute
configuration.Parent = instance
attributeUtil.Display(configuration, value)
else
attributeUtil.Set(instance, attribute, value)
end
end
end
end
do
if isRunning then
local cache = {}
local function isClone(instance: Instance): boolean
return not cache[instance] and attributeUtil.Get(instance, "GUID")
end
local function tagGUID(instance: Instance)
local newGUID = JSON.GenerateGUID(false)
if isClone(instance) then
local previousGUID = attributeUtil.Get(instance, "GUID")
tagUtil.Remove(instance, previousGUID)
end
attributeUtil.Set(instance, "GUID", newGUID)
tagUtil.Add(instance, newGUID)
cache[instance] = newGUID
end
instanceUtil.doForAllDescendantsOf(game, function(descendant: Instance)
pcall(tagGUID, descendant)
end)
end
end
return attributeUtil
return function()
local ReplicatedStorage = game:GetService("ReplicatedStorage")
local Utilities = ReplicatedStorage.Utilities
local attributeUtil = require(Utilities.attributeUtil)
local TestService = game:GetService("TestService")
local dictionary = {
Array = { 1, 2, 3 },
Dictionary = { Employees = { John = { Age = 50 } } },
CFrame = CFrame.new(),
["Instance"] = workspace,
}
dictionary.__index = dictionary
itSKIP("doForAttributeChanged", function()
local connection
connection = attributeUtil.doForAttributeChanged(script, "Test", function(value: string)
connection:Disconnect()
expect(value).to.be.equal("Test")
end)
expect(typeof(connection)).to.be.equal("RBXScriptConnection")
end)
it("YieldUntilValueIs waiting", function()
attributeUtil.waitUntilAttributeIs(script, "Test", "Test"):andThen(function(currentValue: any?)
expect(currentValue).to.be.equal("Test")
end)
end)
it("SetAttribute", function()
attributeUtil.Set(script, "Test", "Test")
end)
it("YieldUntilValueIs already", function()
attributeUtil.waitUntilAttributeIs(script, "Test", "Test"):andThen(function(currentValue: any?)
expect(currentValue).to.be.equal("Test")
end)
end)
it("SetAttributes", function()
attributeUtil.SetAttributes(script, dictionary)
end)
it("GetAttribute", function()
expect(attributeUtil.Get(script, "Test")).to.be.ok()
expect(attributeUtil.Get(script, "Nil")).to.never.be.ok()
end)
it("GetAttributes", function()
local attributes = attributeUtil.GetAttributes(script)
for _, key: string in ipairs({ "Array", "Dictionary", "CFrame", "Instance" }) do
expect(attributes[key]).to.be.ok()
end
expect(attributes["Nil"]).to.never.be.ok()
end)
it("GetChildrenWithAttribute", function()
expect(attributeUtil.GetChildrenWithAttribute(TestService.ServerTests, "Test")[1]).to.be.equal(script)
expect(attributeUtil.GetChildrenWithAttribute(workspace, "Test")[1]).to.never.be.ok()
end)
it("GetDescendantsWithAttribute", function()
expect(attributeUtil.GetDescendantsWithAttribute(TestService, "Test")[1]).to.be.equal(script)
expect(attributeUtil.GetDescendantsWithAttribute(workspace, "Test")[1]).to.never.be.ok()
end)
it("FindFirstChildWithAttribute", function()
expect(attributeUtil.FindFirstChildWithAttribute(TestService.ServerTests, "Test")).to.be.equal(script)
expect(attributeUtil.FindFirstChildWithAttribute(TestService, "Test", true)).to.be.equal(script)
expect(attributeUtil.FindFirstChildWithAttribute(workspace, "Test")).to.never.be.ok()
end)
it("WaitForChildWithAttribute", function()
expect(attributeUtil.waitForChildWithAttribute(TestService.ServerTests, "Test")).to.be.equal(script)
expect(attributeUtil.waitForChildWithAttribute(workspace, "Test", 0.1)).to.never.be.ok()
end)
it("ClearAllAttributes", function()
attributeUtil.ClearAllAttributes(script)
expect(attributeUtil.Get(script, "Test")).to.never.be.ok()
end)
-- it("Display", function()
-- AttributeUtil.Display(script, dictionary)
-- end)
end
MIT License
Copyright (c) [2021] [RuizuKun_Dev]
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
@R0bl0x10501050
Copy link

Small spelling error: "yeild" is spelled "yield".

@RuizuKun-Dev
Copy link
Author

Small spelling error: "yeild" is spelled "yield".

Thank you this will be fixed!

@RuizuKun-Dev
Copy link
Author

RuizuKun-Dev commented Feb 18, 2021

Todo:

  • add Type Check
  • change tick to os.clock
  • use TestEz
  • use t
  • Support using Instance as an Attribute

@RuizuKun-Dev
Copy link
Author

RuizuKun-Dev commented Oct 3, 2021

  • Changed name from AttributeService to AttributeUtil
  • Added CFrame support
  • Added Table support for JSON valid values only: will automatically filter out invalid values
  • Added a new Codec
  • Added a new TestEz spec.lua file

How Instance works:

Currently all SPECIAL_TYPES are given a Header during Encoding to identify what type an Attribute is while Decoding

How Instance serialization works:

Currently all Instances in the game are given an Attribute name "GUID" with a GUID as it's value for reference and this value is also assign as a collection tag to the Instance for identification.

Collection Tags will not replicate on some Services and Instances that are nil to the client or vice versa

@RuizuKun-Dev
Copy link
Author

RuizuKun-Dev commented Oct 5, 2021

Changelog:

  • Fix Encoding: filter now works correctly for Nested Tables
  • Set Attributes will make sure that Attribute name is valid (Names must only use alphanumeric characters and underscore, No spaces or unique symbols are allowed)
  • Table memory address is now shown in a Table Attribute Value

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment