lua-users home
lua-l archive

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


PA wrote:

> function: 0x10ff60
> my very own require     "table"
> table: 0x101b60 <<<< LOOK HERE (mark added by mr. Aleph)
> function: 0x1127d0
> my very own require     "table"
> table: 0x101b60 <<<< LOOK HERE (mark added by mr. Aleph)

This output only shows that require still uses the same old environment.
If you try the attached program, you'll get the following output:

>a env is    old
>testf env is    old
>b env is    old
>a env is    new
>testf env is    old
>b env is    old
>a env is    old
>testf env is    old
>b env is    old
>a env is    new
>testf env is    old
>b env is    old

Which shows that "callee does not inherit the environment of the caller".

PS Also your trick must be upgraded to deal with upvalues. But this is really easy to do with the help of debug.* facilities. PPS And... Thank you. You've shown me some interesting tricks, I've never thought of...







require "testf"

local function clone(f)
  return loadstring( string.dump( f ) ) 
end

old = true

function b()
  print("b env is", old and "old" or "new")
end

function a()
  print("a env is", old and "old" or "new")
  print("testf env is", testf "old" and "old" or "new")
  b()  
end

a()

local newenv = {}

newenv.testf = testf
newenv.print = print
newenv.b = b

setfenv(a, newenv)

a()

local aClone = clone(a)

aClone()

setfenv(aClone, newenv)

aClone()




#include "lua.h"
#include "lauxlib.h"
#include "lualib.h"


int ltest(lua_State *L) {
  lua_getglobal(L, luaL_checkstring(L, 1));
  return 1;
}


int luaopen_testf (lua_State *L) {
    lua_pushcfunction(L, ltest);
    lua_setglobal(L, "testf");
	return 1;
}