lua-users home
lua-l archive

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]


Okay, I got it to work:

v = "m1"

function m1 ()
    print ("hello world")
end

_G[v]()


On Mon, Oct 6, 2014 at 1:15 PM, Scott Morgan <blumf@blueyonder.co.uk> wrote:
On 06/10/14 11:50, Charles Smith wrote:
> It's said that it's not necessary to have forward declarations, but then
> what's wrong with this:
>
>     v = m1
>
>     function m1 ()
>         print ("hello world")
>     end
>
>     v()
>
> But this works:
>
>     function m1 ()
>         print ("hello world")
>     end
>
>     v = m1
>
>     v()

You might be thinking about this in a 'C' way. That is, in C, regardless
of where a function is written in the source, it always exists and is
available from the start of execution (you just need a forward
deceleration to access it).

In Lua, the function only exists from the point the code is reached and
executed. Before that point there is no function.

As such, you don't forward declare functions like you do in C (or C++,
or various other statically compiled languages), you just pass the
function along to wherever it needs to be used, when it's needed, just
like any other variable.

Scott