Search code examples
lua

Forgot to put () into function's name but instead of giving an error, it gave me a new value. Any explanation?


function Closures()
   local b = 0
   return function() 
      b = b + 1 
      return b 
   end 
end 

bruh = Closures 
print(bruh())

The function I showed has a problem: variable bruh assigns into Closures (I forgot to put () with the variable name). Instead of giving an error, it gave me a different result.

function: 0056b7f0

If I add () to the variable name (Closures), I would get the result I wanted

1

As I know, Closures isn't the function name, but a variable that's assigned to the function. Why do we need () in order to make return work? Any explanation? And I can't really get the function "code thing" by returning nothing (It would show nothing if I tried to print a function returned nothing).

EDIT: I just figured out that if I do

print(Closures())--This and 
print(Closures)

I will get some weird function "code":

function: 0077fa8

function 0048bc30

P.S.: This syntax error is came accidentally along with the question.


Solution

  • Functions are values

    I'll use a simpler example to explain:

    Say we have a function func like this one:

    local func = function() return "REEEEE" end
    

    We can assign this function to a new variable like this

    local func2 = func
    

    Now func2 will be a reference to the same function as func, so we can call func2() and it will return "REEEEE".

    When you call print(Closures), you are not executing Closures, you are just passing the function itself to print, so it calls tostring on the function and writes the result to stdout.

    When you assign Closures to bruh, that means btuh now holds the same function as Closures, and calling it will return the inner function. But try the following:

    bruh = Closures 
    print(bruh()())
    

    That should print 1, because calling bruh returns a function and calling that then returns the number.