Anonymous Function Not Working

I need to know why this isn’t working. These values are just placeholders, and are meant to be calculated inside of the function.

image

The intention of this code snippet is for the CanAttack and Player variables to be set by the return values of the function, basically like the picture below, just without actually creating a named function.

image

okay so, let me briefly explain what you’re doing:

local Foo = function()
    print('test')
end

is the same as

local function Foo()
    print('test')
end

When trying to get multiple returning values from a function your second code was correct:

local function Bar()
    return 1, 2
end

local number1, number2 = Bar()
print(number1, number2) -- 1 2

So naturally, the same will be for the anonymous function:

local Bar = function()
    return 1, 2
end

local number1, number2 = Bar()
print(number1, number2) -- 1 2

By the way, why do you want to use local variable = function() end over local function variable() end
???

1 Like

I was just extremely curious if this was doable in LUAu. I guess not. But thanks for the answer, helped out laods :slight_smile:

1 Like

The first code does not work because you declare a function, you are not calling it.

It’s same as this:

function get2Values()
    return 1, 2
end

local var1, var2 = get2Values --This does not work

local var1, var2 = get2Values() --This work

Yeah, I realized. I just really wanted that to give an output. If I used pcall, it would have worked, but it would have been way laggier.

You’re attempting to assign a function value to two separate variables, in Lua functions are recognised as first class values so this won’t run the function and assign the returned values to the variables it’ll just attempt to assign the function itself to the two variables.

There’s a minor difference, after declaring local function Foo, you can access Foo as an upvalue inside the function, meanwhile you can’t in local Foo = function for obvious reasons, instead, local function Foo is the same as local Foo; Foo = function.

For the main question, even though it has been explained why, if you still want to use an anonymous function for whatever reason, you can actually get the anonymous function in parantheses and call it afterwards.

local CanAttack, Player = (function()
	return true, "No"
end)()
-- CanAttack = true; Player = 'No'