lua-users home
lua-l archive

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

On Tue, Mar 17, 2009 at 1:51 AM, <> wrote:
> I don't see how I've a misunderstanding of loading and running a program.
> Rather I seem to have a misunderstanding about  how/when global symbols are
> registered into the global index table. Couldn't find anything in the docs
> about that.

My guess is that your misunderstanding comes from your experience with
other languages.  If we were talking about a language like C, a global
found during compilation would indeed be put into a symbol table and
that symbol table would be accessible to a dynamic loader.  So if we
were talking about C, you could look at the symbol table, determine
there was a named function called START, and then conditionally
execute it.

But Lua doesn't work like C.  As you've already been told in this
thread this is how Lua actually sees your code:

    START = function()

In other words, functions in Lua don't have names.  But you can give
them names by assigning them to variables.  And when does assignment
occur in a program?  That's right, at run-time, not compile-time.

If this still isn't clear, let's look at a disassembly of the code
your START function generates.  Here's the relevant part:

	1	[3]	CLOSURE  	0 0	; 0x9c81e40
	2	[3]	SETGLOBAL	0 -1	; START

In other words, the function you call START is an unnamed blob of code
starting at 0x9c81e40 (that address can and will obviously change).
That unnamed blob of code is only known to Lua's global table in the
second instruction, which sets the function's address to the global
name "START".  Note carefully that I stated this is an *instruction*
so this is *code*.  The SETGLOBAL doesn't happen until you actually
*run* this code.

So hopefully now you understand where your misunderstanding is coming
from.  Setting of globals happens when the code is executed, which is
at run-time.

Now let's go back to the problem you're trying to solve.  I would
suggest something like the following:

First, it sounds like you want a symbol table to know what functions
exist inside the code you're loading.  There are many ways to do that.
 Here is one:

        START = function()

        another_function = function()

That is, wrap your functions in an anonymous table.  That table serves
as your symbol table.  Then after you execute the function you get
from luaL_loadstring, you look into that table for your symbol and if
you find it, dereference and execute it.  You could then choose to
import these functions into your globals if that makes you happy.  You
can also look at Lua's built-in support for modules which automates
much of this and has other nice features.