user3058699
user3058699

Reputation: 111

what is wrong with the function overwritten in lua?

function f()
  return 1
end

function f(N)
  if N == 42 then
    return f()
  else
    return 2
  end
end

f is overwritten, but f(42) returns 2 instead of 1. Why? Is this possible?

Upvotes: 0

Views: 77

Answers (4)

Tom Blodget
Tom Blodget

Reputation: 20782

Your code is equivalent to this:

f = function ()
  return 1
end

f = function (N)
  if N == 42 then
    return f()
  else
    return 2
  end
end

print(f(42))

The first assignment creates a function value and assigns it to f.

The second assignment creates a different function value and assigns it to f. (The first function value is now dead.)

The third statement calls the value of f as a function with an argument of 42.

As others have explained, in the second function, return f(), calls the value of f as a function with no arguments. The value of f at that point is the second function. So, in the second call, N is nil.

Upvotes: 1

vincentp
vincentp

Reputation: 1433

You can't overload a function in Lua. You can just "redefine" it. So :

function f(N)
  if N == 42 then
    return f()
  else
    return 2
  end
end

N = 42, so you call F(N) with N == nil, then it returns 2.

Upvotes: 4

Bartek Banachewicz
Bartek Banachewicz

Reputation: 39380

N is nil in the 2nd case:

f(42) calls f() recursively.

Upvotes: 3

lhf
lhf

Reputation: 72312

N is nil in the second call to f.

Upvotes: 3

Related Questions