How could I set a method to a variable?

Let’s say I’m trying to set TweenService:GetValue(…) to a variable

I can do the following:

local foo = TweenService.GetValue

But then, I have to do this (which does not look good)

foo(TweenService, ...)

I could do this instead:

local foo = function(...)
    return TweenService:GetValue(...)
end

But doing this is tedious and takes a long time

If only I could do this, my problem would be solved:

local foo = TweenService:GetValue

foo(alpha, easing, direction)

And directly using TweenService:GetValue over and over again will just make it look bad

Please help Thanks

Are you talking about saving methods to a variable? Converting them to regular functions?

No like setting a variable to a function

local foo = func

foo()

But with methods

To set a method to a variable just use dot notation and pass in the class as the first variable (self)

Ex:

function Class:DoSomething(...)
end

local DoSomething = Class.DoSomething

--Use case
DoSomething(Class, ...)
--Passing in the class acts like how methods automatically pass self  

Edit: There’s no other way to save a method to a variable other than this (I think)

1 Like

‮‮‮‮‮‮‮‮‮‮‮‮‮‮‮‮‮‮‮‮‮‮‮‮‮‮‮‮‮‮‮‮‮‮‮‮‮‮

You can’t do this unless you use a wrapper function:

local foo = function(...)
	return TweenService:GetValue(...)
end

Though it loses it’s typing unless you manually fill in the parameter names

Other than what you have shown where you pass in the class manually or creating a function that calls the method and passes your arguments, there’s really no other way.

2 Likes

You could create a higher order function that returns a function that automatically passes in the object as the first value

local function CreateFunction(Function, Object)
    return function(...)
        Function(Object, ...)
    end
end

local foo = CreateFunction(TweenService.GetValue, TweenService)
foo(alpha, easing, direction)

Not as convenient as local foo = TweenService:GetValue but probably as close as you’re gonna get

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.