5

I have a function I want to add to dynamically as the program runs.

Let's say I have function Foo:

function foo()
    Function1()
    Function2()
    Function3()
end

and I want to change Foo() to:

function foo()
    Function1()
    Function2()
    Function3()
    Function4()
end

later in the program. Is there any way to do this?

2 Answers2

7

Just do it. The code that you wrote works fine. Functions in Lua can be redefined as desired.

If you don't know what foo does, you can do this:

do
  local old = foo
  foo = function () old() Function4() end
end

Or perhaps it is clearer to use a table of functions:

local F={ Function1, Function2, Function3 }

function foo()
  for i=1,#F do F[i]() end
end

Latter, do

F[#F+1]=Function4

and you don't need to redefine foo.

lhf
  • 70,581
  • 9
  • 108
  • 149
  • @Blauhirn, not strictly, but it keeps the definition of `old` local to that block. – lhf Apr 27 '16 at 12:56
0

This is a supplementary answer with background information.

Lua identifiers are used for global variables, local variables, parameters and table fields. They hold any type of value.

Lua functions are values. Lua functions are all anonymous, regardless of the syntax used to define them.

function f()
--...
end

is a Lua statement that compiles to a function definition and an assignment to a variable. It's an alternate to

f = function()
--...
end

Each time a function definition is executed, it produces a new function value, which is then used in any associated expression or assignment.

It should be clear that neither statement necessarily creates a new variable nor requires it to always have the same value, nor requires it to always hold a function value. Also, the function value created need not always be held only by the one variable. It can be copied just like any other value.

Also, just like other values, function values are garbage collected. So, if f had a function value and is assigned a different value or goes out of scope (say, if it wasn't a global variable), the previous value will be garbage collected when nothing else refers to it.


Without any other context for function f() end, we would assume that f is a global variable. But that's not necessarily the case. If f was an in-scope local or parameter, that is the f that would be assigned to.

Tom Blodget
  • 20,260
  • 3
  • 39
  • 72