lua-users home
lua-l archive

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


I've a very specific question about setfenv. I'm defining a function
"use" that allow to see the functions in a given module, e.g. "math",
like if they were in the global namespace. The adavantage of this kind
of function is that it does not really pollutes the namespace and it
is therefore completely reversible.

It works by replacing the environment variable using a metatable to
intercept the lookups.

In practice, if you have a separate Lua file it works like that:

use "math"

function sinsq(x)
  local y = sin(x) -- I can have access to "sin" as it it was a global variable
  return y*y

The "use" function achieve its goal by defining a new environment
table and using "setfenv" like in the following code snippet:

-- this is not the real code, just a snippt
function use(modulename)
  local env = some_function_to_obtain_a_env(modulename)
  setfenv(2, env)

Actually, what I does works for separate Lua files. The problem is
that I want to enable it for the interactive Lua prompt. For this
purpose I have implemented a sibling function of "use" that does
perform a slightly different task:

function use_alt(modulename)
  local env = some_function_to_obtain_a_env(modulename)
  setfenv(0, env)

So that the global environment is affected.

My questions are :
- it is possible to select automatically the function to use depending if
  the context is a Lua script or a command given in the interactive shell ?
- there is a better way to achive what I'm doing ?

I include the complete implementation so that everyone can look at the
details if needed.

Thanks in advance for any help.


Attachment: import.lua
Description: Binary data