Access a method with a string?

I’m trying to access a event from a instance using a string, example:

workspace.Part:["GetMass"]()

I tried running it but it gave me an error.
Another example from what I’m trying to do.

local function playAnimations(state)
	for _, animationTrack in pairs(animator:GetPlayingAnimationTracks()) do
		animationTrack:[state]()
	end
end
playAnimations("Play")
playAnimations("Pause")

Instead of using if statements, I could just do that so its faster but I don’t really know how…

I am not sure what you are asking.

Can you give an example of what you are trying to accomplish?

When you try to access a method from a instance you do:

workspace.Part:GetMass() --gets mass of the part

And we know we can access properties through strings:

workspace.Part["Name"] = "hi"

I want to know if its possible to access methods:

workspace.Part:["GetMass"]()
local function playAnimations(state)
	for _, animationTrack in pairs(animator:GetPlayingAnimationTracks()) do
if state == "Play" then
		animationTrack:Play()
elseif state == "Pause" then
animationTrack:Pause()
	end
end
playAnimations("Play")
playAnimations("Pause")

Is this what you mean?

Edit: I just fixed the script

just remove the colon symbol

animationTrack[state]()

GetMass() is a built in Roblox function.

["GetMass"]() is a variable followed by a parameter.

I still don’t understand what you want to “happen”.

SampleName() will run a function called SampleName

image

workspace.Baseplate["GetMass"] means you have workspace.Baseplate then another object named "GetMass"

the () is telling the script that it is a function (which is is NOT).

if you want to call a function you need to create one:

local function getMass()
-- script here
end

then call it with getMass()

You can pass the part as an argument:

local Part = --> part
local method = --> method

print(Part[method](Part))

If methodwas GetMass, this code would print the part’s mass.

I can do it by using if statements

local function playAnimations(state)
	for _, animationTrack in pairs(animator:GetPlayingAnimationTracks()) do
		if state then
			animationTrack:Play()
		else
			animationTrack:Pause()
		end
	end
end
playAnimations(true)

But I don’t find a reason to check if the state is true or false for every AnimationTrack. I could’ve just do this and the animation would play.

local function playAnimations(state)
	for _, animationTrack in pairs(animator:GetPlayingAnimationTracks()) do
		animationTrack[state]()
	end
end
playAnimations("Play")

This is what I wanted. Thanks.
image

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