Question

How does returning functions work in Lua? I'm trying to wrap my head around this derivative function but I'm having trouble understanding it.

function derivative(f, delta)
  delta = delta or 1e-4
  return function(x)
      return (f(x + delta) - f(x))/delta
    end
end

Any help is appreciated, thanks.

Was it helpful?

Solution

First see here.

Shortly, functions are first-class citizens and you an store them in variable and return from functions.

Second. In your example there is a closure to be created. It will have upvalues f and delta, wich can be used in inner function.

So when you call your derivative function, new closure will be created with copy of f and delta. And you can call it later like any other function

local d = derivative(f, 1e-6)
d(10)

EDIT: "Answer on but I'm having trouble understanding how the x argument is treated in the anonymous function in my example"

Each function have a signature, number of formal attributes, it will get. In Lua you can call function with any number of arguments. Let's consider an example.

local a = function(x1, x2) print(x1, x2) end
a(1) // 1, nil
a(1, 2) // 1, 2
a(1, 2, 3) // 1, 2

When you call function in variable a, each given argument value, one by one will be matched with function argumentList. In 3-rd example 1 will be assigned to x1, 2 to x2, 3 will be thrown away. In term's of vararg function smth like this will be performed.

function a(...)
  local x1 = (...)[1]
  local x2 = (...)[2]
  // Body
end

In your example x is treated as inner function argument, will be visible inside it, and initialized when you call your inner function instance.

f and delta will be unique for each function instance, as I mentioned above.

Hope my clumsy explanations will hit their goal and help you a little.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top