How to store an Instance function as a variable


I’m currently working on a script which requires a lot of looping and I stumbled upon a guide to optimise your lua code. I saw in there that storing a reference to a function can increase the performance so I tried doing that but I’m unable to figure out how to do that with an Instance function; workspace:Raycast()

Does someone know how to do that?

Thanks !

local object ="Part") -- The Instance
local findFirstChild = object.FindFirstChild -- Index the function using the dot [.] syntax

local child = findFirstChild(part, "ChildName")
-- Because of the nature of how methods on instances work, you have to send the Instance as the first argument

For your example in the post, it would be:

local raycast = workspace.Raycast -- Index the 'raycast' method
local result = raycast(workspace, ...) -- '...' would be the arguments sent to the function

I know how. I do this all the time. Try this:

local funcVar = game.Workspace.Raycast

And that’s it. Make sure you use a period instead of a colon between the instance name and the function name. To call it, you use the variable like a function. So it would look like this:

local result = funcVar([params])

And that’s all there is to it.

Hope this helps.

1 Like

Thanks, it worked ! I forgot to put the “self” argument; workspace which was why it wasn’t working in the first place.