lua-users home
lua-l archive

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


On Mon, Sep 26, 2011 at 09:06:05AM +0200, steve donovan wrote:
> a useful bit of sugar would be:
> 
> import print,table,io
> 
> which makes suitable locals available.  Can also say 'import sin, cos
> from math' of course. 

I find in a file called `dplutils.lua`, this:

~~~~
function util.import(from,items,to)
-- import(from,nil,to) copies everything; can be used as shallow table copy
-- import(from,items,_ENV) copies items to current environment
-- import(from,items) copies items to global environment
-- import(from) copies everything to global environment
-- import(from,foo) replaces foo by a new table if foo is not a table
-- import("name") copies from require "name"
-- if `items` has only one item, it need not be put into a table
-- all versions return the table `to`
    to = to or _G or getfenv()  -- specified or Lua 5.2 or Lua 5.1 
-- FAQ: Why make _G the default, not _ENV?  
-- Ans: Otherwise in interactive mode nothing happens past the current line.
    if type(from)=='string' then from=require(from) end
    if type(to)~='table' then to={} end
    if type(items)=='string' then items={items} end
    if items 
        then for i=1,#items do to[items[i]] = from[items[i]] end 
        else for k,v in pairs(from) do to[k]=v end
        end
    return to
    end
~~~~

I'm sure most of you have something of the kind, probably a little
more sophisticated.

Sure, I start every program with 

    util = import "dplutils"
    util.import(util)

but is the proposed 'import sin,cos from math' really so much more 
convenient than 'import(math,{"sin","cos"})' as to justify two new 
keywords?  (As I have confessed before, I'm a Python _apostate_).

Dirk