How do I make an anonymous function?

Hello fellow Devs!

I feel pretty dumb for asking this but, I thought I could create an anonymous function like so:

local val = spawn(function() v = "test value" return v end)
print(val)
--or 
local val = function() v = "test value" return v end
print(val)

However, when I try this, it returns a nil value or an error.

What am I missing, or is it not Lua but another language like C# that you can do this in?

o_o?..

Thanks!

spawn does not return the value returns by the passed body function. I recommend using the coroutine library if you want further control over the ‘threads’ you create:

local co = coroutine.create(function()
    return "test value"
end)
local isSuccessful, val = coroutine.resume(co)
print(val) --> test value

Or, to be more concise:

local val = coroutine.wrap(function()
    return "test value"
end)()
print(val) --> test value

You can learn more here.

Here, you’re forgetting to call the function:

local val = (function() return "test value" end)()
print(val)
3 Likes

The first example should result in nil, as spawn has no return value. The second example has no error, the result should be function: 0xABCDEF or something like that. That is the function’s hexadecimal memory address.

Btw all function in Lua are anonymous.

1 Like

Your 2nd example shouldn’t error.
By ‘anonymous function’ in lua people usually refer to functions created without name, i.e. directly inside a function’s call arguments, like so:

event:Connect(function()
    print("im an anonymous function!")
end)

However doing this:

local function a()
    print("hi, my name is a")
end
local b = function()
    print("hello, I'm b")
end

is considered creating a non-anonymous function (although some people might argue about the 2nd one).

With that being said, if you want to create an anonymous function just to get a single value, you can wrap it in () parantheses and then call it at the end:

local val = (function() return 1+1 end)()
print(val) --> 2

As you can see, anonymous functions can be created without putting them inside a function call :slight_smile:

Btw you should avoid using global variables when possible (referring to your example code).

2 Likes

local val = (function() return “test” end )()
This function will not be present as a variable, only its returned value will.

1 Like