Scripting Helpers is winding down operations and is now read-only. More info→
Ad
Log in to vote
1

Instant change in appearance when modifying a property of a custom class?

Asked by
Y_VRN 246 Moderation Voter
2 years ago

If the title isn't really clear...

Let's say I have Window.new() - built with a Frame, and a bunch of other TextLabels, TextButtons, etc. - and I want to edit its Size property. Just like ordinary Frame objects, I want the new Window to resize as soon as its custom Size property is changed. But because the Window class has custom properties, specifically the Size property, that initially had no control over the size GUI, I need to know how I could mitigate this.

I, unfortunately, have not enough relevant code to show, and as far as my research with custom classes go, I can't seem to find the info I need, so I am currently clueless. My only guess is using __index metamethod, yet I still do not know how I should implement it.

Do I really have to use the __index metamethod for this? And if so, how?

Thanks in advance.

1 answer

Log in to vote
0
Answered by
7z99 203 Moderation Voter
2 years ago
Edited 2 years ago

No, you shouldn't need the __index meta method for this. You could, instead create a new BindableEvent and whenever the custom size property is changed, fire this BindableEvent. The only downside is that you would have to use a custom function or a proxy table to know when the custom Size property is changed. The proxy table would use __index and the __newindex meta methods though.

local window = {}
function window.new()
    local newWindow = {}
    local internalEvent = Instance.new('BindableEvent')
    newWindow.SizeChanged = internalEvent.Event -- assigns the BindableEvent's Event event to the .SizeChanged property/event
    newWindow.Size = UDim2.new(1,0,1,0)
    -- you can choose this method, a proxy table
    local newWindow = setmetatable({}, {
        __index = newWindow;
        __newindex = function(self, index, value)
            if index == 'Size' then
                internalEvent:Fire()
                rawset(newWindow, 'Size', value)
            else
                return newWindow
            end
        end;
    })
    -- or this, which is better if you don't understand why above works
    function newWindow:AdjustSize(newSize)
        internalEvent:Fire()
        window.Size = newSize
    end
    --
    return newWindow
end
--elsewhere,
local window = window.new()

window.SizeChanged:Connect(function()
    print('Size changed!')
end)
-- if you went the proxy table route,
window.Size = UDim2.new(1,0,0,0)
-- if you went the function route,
window:AdjustSize(UDim2.new(1,0,0,0))
Ad

Answer this question