ANNOYING Luau behaviour is not letting me pass a function as an argument to a function

I want to grab the function of the service itself, but I can’t because Luau behaviour thinks I intend to call it. This is weird, as passing a function that I make will work perfectly fine, but functions from services do not work and thinks I intend to call it. Passing the function of the service to the print function will work fine too. I’m guessing that I can’t pass C closures as an argument to a function, and I can only pass Lua closures. This is really weird, but in the code below, how would I pass the C closure (TestService.Message) to the L closure (GetFunction) without it erroring?

function GetFunction(f: funct): funct
	return coroutine.wrap(function(...)
		while true do
			coroutine.yield(f(...))
		end
	end)
end

task.spawn(function()
	local testfunc = function()
		print("hey")
	end
	
	local _testfunc = GetFunction(testfunc)
	_testfunc() -- this one works perfectly fine and prints hey
end)

task.spawn(function()
	local TestService = GetService("TestService")
	local Message = GetFunction(TestService["Message"]) -- this grabs the function, as the service that GetService returns is a metatable, not an instance. doing this does not work either: TestService.Message
	Message("hey") -- ServerScriptService.Script:27: Expected ':' not '.' calling member function Message  -  Server - Script:27
end)

The screenshot below shows that “hey” has been printed and did not error, but passing TestService.Message to the argument of the function does error:

The issue is you’re completely ignoring what the error message is telling you, the : operator is used as syntax sugar for this:

local t = {
	message = 'hello'
}

function t:sayHi()
	print(self.message)
end

t:sayHi() --is the same as
t.sayHi(t)

meaning that to make your code work you would have to do

Message(TestService, "hey")

Edit: this also means that what is actually happening when you call the :Message() function is this:

TestService.Message(TestService, message)
4 Likes

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