Reassigning function to a value

Viewed 54

I don't understand why exactly is happening/why I am not getting an error when doing somefunc() = 100? Now when I "call" somefunc, it outputs 100. I also tried just doing somefunc = 100, which then gives me an error. After reassigning somefunc() to 100, when I just write somefunc, it still says it is a function.

What exactly is happening here? Why do I get an error when reassigning somefunc to a value, but when reassigning somefunc(), not? Why does somefunc still say it is a function, even after reassigning it?

1 Answers

When you write somefunc() = 100 in global scope you define a new method for the somefunc function. This has two effects:

  1. If somefunc is undefined, make it a constant (i.e. cannot be reassigned like const x = 123) binding to a new generic function.
  2. Whether it's new or not add a method for () -> 100 to the somefunc generic function object.

The fact that the binding for somefunc is constant is why you cannot reassign it afterwards. This is very important for performance since non-constant globals have quite bad performance; if function bindings were not constant then any time you called a function it would be slow.

Even though you cannot change what function somefunc refers to, you can change the function itself by adding methods to it or even overriding existing ones. For example, writing later somefunc() = 200 does not create a new function, but rather replaces the method of this function taking no arguments with a new method that returns 200 instead of 100.

When you write:

somefunc() = 100

it is just a shorthand for

function somefunc()
    return 100
end

So even though there is a = sign, that is an assignment operator it is not the same as writing x = 100, which simply binds the value 100 the name x. In particular note that writing e.g.:

somefunc = () -> 100

allows you to write somefunc(), and get 100. But this time you are free to write later somefunc = 100, as somefunc = () -> 100 is not a function definition but rather it is na assignment that binds the anonymous function () -> 100 to the name somefunc.

Related