lua-users home
lua-l archive

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


2013/4/16 Hisham <h@hisham.hm>:

> That's why what I always wanted from the module system, instead of the
> wild-west of package.seeall, was a way to get a guaranteed "reset"
> environment (like a 'package.seebase' of sorts) with only the standard
> Lua globals. If Lua can construct a default environment for the main
> chunk and populate the standard libraries there, I figure it could
> just as well do the same for modules, to ensure that module authors
> can work with a stable set of assumptions about the environment, just
> like script writers do.

Well, as long as you grant me a working 'require' or 'dofile',
and also 'pairs', I can do that.

$ lua
Lua 5.2.2  Copyright (C) 1994-2013 Lua.org, PUC-Rio
> oldprint = print; print = function() oldprint"Sorry, 'print' has been clobbered." end
> math, io, string, table = nil
> junk="junk"
> x=math.sin(math.pi/6)
stdin:1: attempt to index global 'math' (a nil value)
stack traceback:
	stdin:1: in main chunk
	[C]: in ?
> print(1,2,3)
Sorry, 'print' has been clobbered.
> local require=require; for k in pairs(_ENV) do _ENV[k]=nil end; require"reset"()
> return junk
nil
> x=math.sin(math.pi/6)
> print(1,2,3)
1	2	3

So what is this magic module "reset"? Its complete C source code is
attached.
#include "lua.h"
#include "lauxlib.h"

static int reset(lua_State *L) {
   luaL_openlibs(L);
   return 0;
}

LUAMOD_API int luaopen_reset (lua_State *L) {
   lua_pushcfunction(L,reset);
   return 1;
}