What is "end)()" used for in roblox lua?

Hey guys, so I have been investigating this for a while now and I haven’t found any answers.

What is end)() used for?

Example of a function where I have seen it:

coroutine.wrap(function()
			local hurtclone = hurt:Clone()
			hurtclone.Parent = WHAT
			for i = 1,4 do
				wait(1)
				humsomeone.Health = humsomeone.Health - 327667.5
				if humsomeone.Health > 0 then
					hurtclone:Play()
				end
			end
		end)() -- ???

I thought it was just a simple add-up to the normal end) so I tried it on an event too but I had gotten this error: attempt to call a RBXScriptConnection value

This was my event:

VAR_petsButton.MouseButton1Up:Connect(function()

if VAR_petList.Position == POS_petListClosed then
    
    VAR_petList:TweenPosition(POS_petListOpen, Enum.EasingDirection.Out, def_chooseRandomEasingStyle())
    
else
    
    VAR_petList:TweenPosition(POS_petListClosed, Enum.EasingDirection.In, def_chooseRandomEasingStyle())
    
end

end)()

Thank you!

coroutine.wrap() creates a function, and you are calling it with ()

On the other hand, :Connect creates a RBXScriptConnection, which is not a function

1 Like

basically in short terms you add “()” to call a function
doesn’t work on signals

To add on to this:

coroutine.wrap takes a function as an it’s first parameter. The inputted function is in this format:

function()
--code
end

coroutine.wrap also returns a function, so that function is called with a pair of ().

Here is the code broken up:

coroutine.wrap(function()
	local hurtclone = hurt:Clone()
	hurtclone.Parent = WHAT
	for i = 1,4 do
		wait(1)
		humsomeone.Health = humsomeone.Health - 327667.5
		if humsomeone.Health > 0 then
			hurtclone:Play()
		end
	end
end)() -- ???

v

local inFunction = function()
	local hurtclone = hurt:Clone()
	hurtclone.Parent = WHAT
	for i = 1,4 do
		wait(1)
		humsomeone.Health = humsomeone.Health - 327667.5
		if humsomeone.Health > 0 then
			hurtclone:Play()
		end
	end
end
local outFunction = coroutine.wrap(inFunction)
outFunction() -- ???

Oh! That makes so much sense lol! I never thought of that.

1 Like

Also, you are able to call functions like that. You can also pass arguments inside of the second pair of parentheses.

local number = (function(num)
    return num
end)(3)
print(number) --> 3

I use this personally in my modules to allow code that only has to run once, to run once. I think it’s a cool little alternative to _G variables.

local module = {
    ['Parts'] = (function()
        local tbl = {}
        for i,v in pairs(workspace:GetDescendants()) do
            if v:IsA('BasePart') then
                tbl[#tbl + 1] = v
            end
        end
        return tbl
    end)()
}

return module
2 Likes