Cloning a function?

Is it possible to clone functions? Kinda like table.clone(...).

If you mean like, the actual code, then I guess you could use script.Source and parse for what you’re looking for ?

I dont really see why you would want to clone a function, you can probably just use a ModuleScript to share the function if thats what you’re trying to do.

Just make a new variable and set it to the function you want to clone. May I ask why you need this?

That is what I’m doing. I’m using an OOP class to represent enemies, and each enemy has a predefined set of functions and such. One of these functions is the AI for the enemy, which is constantly running. When another enemy calls the exact same reference, the AI is overriden and switches to the new enemy.

(basically: You need an enemy AI per enemy and since there is only one it is overridden a bunch and stops working for the other enemies.)

1 Like

That isn’t necessarily cloning the function, that just creates another reference to it, providing an alternative way to call it.

I don’t honestly see the difference, as it is different from the original.

instead of cloning the function, you can call the function inside the second function…

1 Like

I didn’t really get what you meant, did you mean something like this?

function newAI()
	return function(...) --creates and returns an anonymous function every time it is called
		... --AI code here
	end
end

Script:

local AI = newAI() --gets a new anonymous function
AI(...)

Edit: In case anyone else is struggling with the same issue, this method is the solution. I don’t think it’s really possible to ‘clone’ a function but you can create a new anonymous function any time you need it.

You could optimize the function to work within the given parameters or use a coroutine to run the function in the background.

Informations on devhub:

Devforum post:

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