lua-users home
lua-l archive

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

On Tue, Sep 29, 2009 at 7:40 PM, Mark Hamburg wrote:
> It would be nice to have a way
> to say essentially "the following portion of the program text should form a
> syntactically valid Lua chunk which should be encoded as a loadable string"....
> We could get around this by passing functions and dumping them to bytecode
> strings....However, we have to be
> careful to ensure that the functions so used do not have any upvalues...
> But imagine a chunk keyword (anathema I know to add a keyword, but imagine
> it none the less). This keyword basically works just like "function" but it
> returns the bytecode for the chunk and does not capture upvalues.

You can check at run-time whether a given function has upvalues via
"debug.getupvalue(f,1) == nil", which is basically bytecode
inspection.  Analogously, you can also detect access to globals
(checkglobals [1]).  Would that be enough?  As with [1], it wouldn't
be that much work to write a tool to also statically verify the
absence of upvalues (e.g. with luac -p -l, Metalua, patched luac,
etc.) provided the given functions are annotated in some way.  For
example, in luaanalyze it could be

     --! noupvalues()    -- this will error at compile time if the
current function has upvalues
     msg = luaproc.receive("achannel")

or inversely,

  --! luacode()    -- this will error at compile time if the
subsequent string is not valid Lua
  [[ msg = luaproc.receive("achannel")
     print(msg) ]]

or more transparently

  luacode [[ msg = luaproc.receive("achannel")
                 print(msg) ]]

where luacode is the identity function at runtime but assumes the
meaning of "--! luacode()" in the lint tool.

That said, there have been occasions where I wanted something like you
suggest, except that the called function wants the original source,
not just the bytecode.  Use cases might involve code generation [2],
metaprogramming, debugging, or serializing a data structure back to
disk in original source code form.  There have been proposals to allow
the source code for a function to be obtained [3], which would address
this.  A more extensive approach is Metalua, which provides you full
access to the AST.