Not understanding what a Higher-Order Function is (HOF)

I’m trying to make efficient good looking code in my script and I come across a problem where I can’t access the part I used a .Touched event on inside a local function.

I ask the AI assistant and it shows a HOF which puts a function itself into the argument and returns the Touched event as a function.


I don’t understand how this works and how a local function with the instance being touched as the argument can work while returning the actual touched function inside of the createCollectBananaFunction.

And why wouldn’t it work, exactly? Also, keep in mind there is an alternative to this approach, which is to inline the function. This would allow you to access the up-values (variables outside, or above the anonymous function’s scope).

The AI is suggesting to decouple the .Touched high order function from the .Touched event. This is sometimes useful if you want to build new .Touched functions but with slight modifications.

There is no need to do the HOF unless you plan on reusing it in different types of hitboxes in the code, which you’re not doing. You’re using it only on all BananaHitboxes.

This is the same thing:

CollectionService:GetInstanceAddedSignal("BananaHitbox"):Connect(function(instance)
	instance.Touched:Connect(function(hit)
		print(instance, "touched", hit)
		-- touched function
	end
end)
2 Likes

I think it isn’t right though how I would be repeating the same lines of code instead of just putting it into a function and getting the same result. (I’m using the touched event for a for loop and the GetInstanceAddedSignal because some hitboxes do not register in the GetInstanceAddedSignal.)

I don’t understand how this works and how a local function with the instance being touched as the argument can work while returning the actual touched function inside of the createCollectBananaFunction.

In Lua, functions are first-class values, which means they can be stored, passed and returned like any other variable.

function bar()
  return 2 + 2
end

function foo()
  return bar()
end

print(foo()) -- returns 4
1 Like

How is it possible to put arguments inside the function inside the built-in function?

Explain. Do you mean the Touched:Connect(function() end) block, or something else?

Event:Connect(function() print("Touched") end)

is syntactic sugar for

function foo()
  print("Touched")
end

Event:Connect(foo)

You’re just using an anonymous function, the function() print("Touched") end), instead of a defined one, foo(). The arguments are just being established within the anonymous function:

function(a, b, c) print(a + b + c) end)
1 Like

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