lua-users home
lua-l archive

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


Hi! I was hoping an expert in the internals of Lua would help me get started
on a new project. Basically I want to add an extra feature to the Lua API
which generates a Lua function and returns it on the stack. At the moment
I'm just looking for the basic framework to achieve that. Here is my effort
so far:

LUA_API int luaX_engram (lua_State *L) {
  int pc;
  Proto* f = luaF_newproto(L);
  Closure* cl = luaF_newLclosure(L, 0, NULL);
  cl->l.p = f;
  setclvalue(L, L->top, cl); incr_top(L);

  f->source=luaS_newliteral(L,"=(ENGRAM)");
  f->maxstacksize=1;

  f->p=luaM_newvector(L,1,Proto*);			//Space for one
inner function
  f->p[0] = clvalue(L->top-2)->l.p;			//Insert the inner
function
  f->sizep = 1;

  pc=3;							//Number of opcodes
  f->code=luaM_newvector(L,pc,Instruction);	//Space for opcodes
  pc=0;
  f->code[pc++]=CREATE_ABx(OP_CLOSURE,0,0);	//Create closure from inner
function
  f->code[pc++]=CREATE_ABC(OP_CALL,0,1,1);	//Call the inner closure
  f->code[pc++]=CREATE_ABC(OP_RETURN,0,1,0);	//Return from outer function
  f->sizecode=pc;
	
  return 0;
}

I recompiled Lua including this code without problems and it runs OK
producing a Lua function as expected, however executing the returned
function gives an exception (puzzlingly in a table key lookup function). The
above function is called with a Lua function at stack top (the inner
function) and is supposed to return a Lua function (the outer function). At
present, when the outer function is executed it is just supposed to run the
inner function.

Can anyone spot what I am doing wrong? If the basic method is wrong, could
anyone give me a re-write?

For background, where I am trying to get is to use the string.dump format as
a message serialisation / data persistence format. What I call an "engram"
will be a function which encapsulates an inner function and a variable
persisted as constants. When the engram is executed it will execute the
inner function and pass it the reconstructed variable.

Attachment: smime.p7s
Description: S/MIME cryptographic signature