function SyncToAttribute(target, name, variable)
local function sync()
variable = target:GetAttribute(name)
end
sync()
target:GetAttributeChangedSignal(name):Connect(sync)
end
local HeadHorFactor = 0
SyncToAttribute(script, "HeadHorizontalFactor", HeadHorFactor)
I want to update the variable whenever attribute value changes but I dont want to write 5 extra lines of code for every variable that I want to sync with attribute. How can I do that? Since I cannot change variable contents, only in the scope.
I also tried to do this with Proxy module but I kept getting “C stack overflow” errors.
I don’t understand your question, it’s hard to read - sorry. Could you clarify it a bit?
It sounds like you just want an array of attribute names (or use GetAttributes to get a key/value of all of them) and then use a for loop to connect a changed signal to each one.
I want to update my variable whenever the attribute value changes using a function instead of writing 5 lines of code for each variable.
local y = script:GetAttribute("y") --> 0
print(y) --> 0
script:SetAttribute("y", 1)
print(y) --> 0
-- as you can see, y still gives 0
There is a solution to do that, but its cluttering my code
local TurnCharacterTowardsMouse = false
local function UpdateTurnCharacterTowardsMouse()
TurnCharacterTowardsMouse = script:GetAttribute("TurnCharacterTowardsMouse")
end
script:GetAttributeChangedSignal("TurnCharacterTowardsMouse"):Connect(UpdateTurnCharacterTowardsMouse)
UpdateTurnCharacterTowardsMouse()
So I want to make function that updates the variable whenever the attribute value changes instead of writing this mess above. Such as SyncWithAttribute(script, "TurnCharacterTowardsMouse", TurnCharacterTowardsMouse).
local function attributeChanged(attributeName)
getfenv(0)[attributeName] = script:GetAttribute(attributeName)
end
script.AttributeChanged:Connect(attributeChanged)
The variable names must be the same as the attribute name for this to work. Consider the comment below.
You’re going to need that boilerplate. Variable definition in Luau hasn’t changed with the addition of attributes, the value of a variable will be whatever it is at the time of assignment. You need to update it yourself, even if it’s just as simple as using GetAttribute just before using it.
I do not recommend the above code because using getfenv/setfenv disables Luau optimisations.