How to immediatley run function without setting it to a variable

I’ve been trying to do this to shorten code and this is by far what takes up the most space, there are plently of times i have to run a function to use return but only use that function once, is this possible?

The purpose of a function is to reduce clutter by reusing code. If a function is only to be ran once, then a function is not needed. I’m not sure if I understand what you mean completely, so could you please elaborate on what your situation is?

I do need it because i want to establish a return based on some conditions, so i need a function for that. but i will only use it once.

Do you mean something like this?

local result = (function()
   return "result"
end)()
1 Like

What do you mean?

local function doSomething(a, b)
   if a then
     return true
   elseif b == 2 then
     return false
   end
end

local Value = doSomething(false, 1)

Can be made simpler by simply:

local Value

if a then
  Value = true
elseif b == 2 then
  Value = false
end

Wow i didn not know you could do that, makes sense though :pray:t2:

Don’t do that - if you really want to do something like that, do:

local result do
  result = "result"
end

print(result) -- "result"

It is a waste of memory to create single-use functions. You should always write your code with efficiency in mind.

1 Like

I still don’t get why you even need this at all

I’ll give you an example, hopefully this is kind of understandable:

game.ReplicatedStorage.BindableFunction.OnInvoke = function()
return (function if math.random(1,2) == 1 then return "this" else return "that" end end)()
end

This is shorter than other methods for writing this, which is what i was looking for.

That doesn’t make sense. Returning data to a BindableEvent event is pointless…

2 Likes

why can’t you do this instead

game.ReplicatedStorage.BindableEvent.Fired:Connect(function()
    return math.random(1, 2) == 1 and "this" or "that"
end)
3 Likes

It just doesn’t work for what i have in mind.

I mean it returns the exact same thing, but ok I guess

1 Like

???

game.ReplicatedStorage.BindableFunction.OnInvoke = function()
     if math.random(1,2) == 1 then 
         return "this" 
     else 
         return "that" 
     end
end

As @D0RYU suggested, using shorthand statements with and and or can make your code tidier, but I understand they can’t be used in every situation, so I’ve provided you with a solution that should always work.

1 Like

that reminds me, why is @b0r_4li5 returning inside a bindable event
makes 0 sense

Ik, was just example didn’t think that through lol.