lua-users home
lua-l archive

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


On Feb 21, 2013, at 6:50 PM, James Graves <james.c.graves.jr@gmail.com> wrote:

> So, my main question is: Is there any way to have some kind of import
> statement (for regular Lua) that doesn't require passing in the
> current _ENV value?  Where I just have this:
> 
> import 'foo.bar'
> 
> and have a table named 'bar' in the local environment (not global).

Sure there is… for example:

import( 'math', 'min', 'max' )

print( min )
print( max )

> function: 0x10001ac20
> function: 0x10001aba0


And 'import' could be defined along the following lines or something:

local function import( aName, ... )
  local aModule = require( aName )
  local aFunction = debug.getinfo( 2, 'f' ).func
  local _, anEnvironement = debug.getupvalue( aFunction, 1 )

  for anIndex = 1, select( '#', ... ) do
    local aName = select( anIndex, ... )
    anEnvironement[ aName ] = aModule[ aName ]
  end
end


Still… it's not because one could, that one should... 

"All Magic Comes at a Price Dearie" -- Mr Gold