[Date Prev][Date Next][Thread Prev][Thread Next]
- Subject: Re: When are global names registered within th VM?
- From: John Passaniti <john.passaniti@...>
- Date: Tue, 17 Mar 2009 03:43:46 -0400
On Tue, Mar 17, 2009 at 1:51 AM, email@example.com <firstname.lastname@example.org> 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
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  CLOSURE 0 0 ; 0x9c81e40
2  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
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.