lua-users home
lua-l archive

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


<snip>
> I do not know what do you mean by "different approach to their problem".
<snip>

How about this approach?

#include <lua.h>
#include <lauxlib.h>

static int loadenv_caller (lua_State *L) {
  lua_settop(L, 1);
  lua_pushvalue(L, lua_upvalueindex(1));
  if (lua_type(L, 1) == LUA_TTABLE) { /* set env? */
    lua_pushvalue(L, 1);
    lua_setfenv(L, -2);
  }
  lua_replace(L, 1);
  lua_call(L, 0, LUA_MULTRET); /* call chunk */
  return lua_gettop(L);
}

static int loadenv (lua_State *L) {
  lua_rawgeti(L, LUA_REGISTRYINDEX, LUA_RIDX_GLOBALS);
  lua_getfield(L, -1, "load");
  lua_replace(L, -2);
  lua_insert(L, 1);
  lua_settop(L, 4);
  lua_call(L, 3, 1); /* load */
  lua_pushcclosure(L, loadenv_caller, 1);
  return 1;
}

int luaopen_loadenv (lua_State *L) {
  lua_pushcfunction(L, loadenv);
  return 1;
}

$ lua
Lua 5.2.0 (work1)  Copyright (C) 1994-2008 Lua.org, PUC-Rio
> loadenv = require"loadenv"
> f = loadenv"print(a)"
> f()
nil
> f{print=print, a=math.pi}
3.1415926535898

Cheers,
Luis

-- 
Computers are useless. They can only give you answers.
                -- Pablo Picasso

-- 
Luis Carvalho (Kozure)
lua -e 'print((("lexcarvalho@NO.gmail.SPAM.com"):gsub("(%u+%.)","")))'