How to make a function fire without having to call it first?

Hello!

I need to figure out something ‘simple’.
How would I go about, firing a function at the start of a script without having to call it?

If I suck at explaining, this is what I mean:

function foo_() -- assign function
   print("lorem ipsum")
end

foo_() -- BAD!!! we have to call it !!!! I DONT WANT THAT!!! I WANT IT TO FIRE AUTOMATICALLY!

^ This

This is what I want to achieve:

function foo_() -- assign function, but make it fire without having to call it!!!
   print("--im mindfrayed")
end
-- output:
--im mindfrayed

-- function fires without having to call it at the end of the script!!!

How would I achieve this? Is it even possible ???

Functions are made to be called by another function or thread, if you don’t want that simply put the code block outside the function within the thread.

Else you’re just trying to figure out a smart/suspicious way to run code that can easily turn into a security risk if utilized the wrong way.

However technically you can call a function without calling it by connecting it to an event and firing it.

2 Likes

you can’t‎ ‎ ‎ ‎ ‎ ‎ ‎ ‎ ‎ ‎ ‎ ‎ ‎ ‎ ‎ ‎ ‎ ‎ ‎ ‎ ‎ ‎ ‎ ‎ ‎ ‎

What is the goal here? I know it’s to run a block of code within a function without calling the function, but why do you need this behavior?

are you just referring to this?

(function ()
	print"--im mindfrayed"
end)()

--didnt even assign it to any variable, immediate execution
-- meanwhile function foo_() declares it to the namespace
2 Likes

yes, that’s what i was looking for. sorry for being UNCULTURED. thanks king!!! :heart:

1 Like

There’s not really any reason why you would need to define a one off function that runs immediately.

Are you doing it to allow for local variables to be used just within that particular area? If so, you can instead do

do
    print("hello")
end
1 Like

no, i was just trying to go for this because using functions helps me organize my code better- even if they can sometimes be unnecessary. that’s just how i script.

I mean… I’ve seen some valid use cases to just “simplify” code

local myRemote =       --creates the remote if it cant find it
	ReplicatedStorage:FindFirstChild('myRemote') or (function()
		local remote = Instance.new('RemoteEvent')
		remote.Name = 'myRemote'
		remote.Parent = ReplicatedStorage
		return remote
	end)()

myRemote:FireClient() --ready to use!

instead of the alternative:

local myRemote = ReplicatedStorage:FindFirstChild('myRemote')

if not myRemote then
	myRemote = Instance.new('RemoteEvent')
	myRemote.Name = 'myRemote'
	myRemote.Parent = ReplicatedStorage
end

cause whats the fun in using if statements?

1 Like

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