lua-users home
lua-l archive

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

Further thoughts on the use+mention problem, where we have to repeat a
name to use it as a variable and to mention it as a table index or
function argument. The main examples are:

  local name = name            -- keep name in scope after altering _ENV
  local name =     -- import unqualified name from module
  local name = require "name"  -- module linkage
  { name = name }              -- export variable into table

The usual proposal to improve the first two is as follows, but I'm trying
to find a more general solution.

  local name in _ENV
  local name in module

I call the first three "projection" from a table or function into
variables and the last one "injection" from variables into a table.

It seems to be helpful to think of both projection and injection as
special kinds of assignment. This emphasizes their duality, and it
suggests a better syntax for injection.

So the syntax for projection might be like

  foo, bar, zig <- tbl

where "foo, bar, zig" is a list of variable names and "tbl" is an
expresion. The "<-" is pronounced "from" as in "assigned from" or
"imported from". This is equivalent to

  foo, bar, zig =,, tbl.zig

except that tbl is evaluated once. A projection statement starting with
"local" has the obvious translation:

  local foo, bar, zig <- tbl
  local foo, bar, zig =,, tbl.zig

Injection might be like

  tbl -< foo, bar, zig

which is equivalent to,, tbl.zig = foo, bar, zig

with the same conditions as before. Injection needs a different operator
so you can tell the difference between "x <- y" and "y -< x". The "-<"
symbol is the syringe operator.

I think on balance it doesn't make sense to support projecting from
functions directly. This avoids muddling the concepts of indexing and
calling, but you can still use the __index metamethod if you want. For

  -- syntactic sugar for require

  library = setmetatable(package.loaded, {
              __index = function (_, name)
                          return require(name)

  -- get math and io modules from the library

  local math, io <- library

f.anthony.n.finch  <>
Dover, Wight, Portland, Plymouth: Northwest 4 or 5, increasing 6 at times,
backing west 3 later. Slight or moderate, occasionally rough in Plymouth at
first. Showers. Good.