Public properties module (use attributes effectively)

Today I was working with attributes in a mathematical animation. it wasn’t very easy or efficient to deal with.

whenever I wanted to retrieve an attribute. I have to write a gigantic line. and if the call is inside of a high performance loop. it’s an overkill since you’re calling a global studio function that interacts with the C API and retrieves the value for you everytime. while you can cache it yourself instead.

Features:

  • Caching attributes locally
  • The ability to edit variables in studio live like unity and other engines without any extra code
  • Faster and more efficient to work with

So I made this simple module:

-- local Public = require(game:GetService("ReplicatedStorage"):WaitForChild("Public"))

return function(instance)
	local G = {}
	for attribute, value in pairs(instance:GetAttributes()) do
		G[attribute] = value
	end
	local function AttributeChanged(attribute)
		G[attribute] = instance:GetAttribute(attribute)
	end
	instance.AttributeChanged:Connect(AttributeChanged)
	return G
end

now in your script just do the following:
Let’s say I have a script inside of a part.
The part contains two attributes called Pizzas and Tacos
Here is what the script that prints their values look like

local Public = require(game:GetService("ReplicatedStorage"):WaitForChild("Public"))

local G = Public(script.Parent)

print(G.Pizzas)
print(G.Tacos)

Tutorial:

1 Like