lua-users home
lua-l archive

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


OK, I'm going out on a limb with this response, but this thread is annoying
me.

If you can do something in Lua script then you can do it from C.  Period end
of discussion.
Well, OK, not quite end of discussion.

The following comment prompted this response...
> Because when I write in my scriptfile
>  local SomeVar;

If that is the case, then (while it may not be the most elegant solution)
you should have no problem overcoming this.  Just use the interpreter to do
the work for you.

For example (WARNING: POSSIBLE OVER-SIMPLIFICATION), rather than just
coding...
    lua_dofile(L, ScriptFile);

code...
    lua_dostring(L, "local SomeVar;");
    lua_dofile(L, ScriptFile);

Surely that is clear enough.  However, there is a possible problem with Lua
lexical scoping in this regard.  That problem is that dostring, dofile, and
friends will first load the supplied Lua code as a chunk, which is
effectively an anonymous function (at least according to the documentation).
This means that rather than placing "local SomeVar;" in the same scope with
the contents of ScriptFile (or even an enclosing scope), it will place
"local SomeVar;" in a scope that immediately precedes the scope containing
the contents of ScriptFile.  If this is indeed a problem, then at the very
least you should be able to overcome it by writing your own ChunkReader that
injects whatever you wish to inject into a chunk before/after the contents
of the string/file/whatever that is being loaded.  A side issue here is that
you may have to restrict the string/file/whatever to only contain textual
(i.e. non-precompiled) script code, otherwise you will have to figure out
how to generate bytecode that isn't already chunked.

----
Another line of attack.  You could change the environment of the loaded
chunk (again a chunk is effectively a function, the manual even says that
the loaded chunk is returned at the top of the stack as a Lua Function, and
environments are specific to functions).  The manual isn't very clear on
exactly what is in an environment, but the obvious solution is for it to
directly contain the variables available to a function from "outer" scopes.
It may be more complicated that this in the actual implementation, but it is
a simple thing to examine an environment to try to figure them out.  As the
global table contains the global table at index "_G", I would assume
function environments do as well.  At any rate, someone more knowledgeable
can pick up this discussion (or you can just go poking around in the tables
and in the source).