lua-users home
lua-l archive

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


On Apr 8, 2014, at 4:41 PM, Coroutines <coroutines@gmail.com> wrote:

> I would like to see the 'in' keyword patch added to enable this: local byte, reverse, gsub in require ‘string'

Of course, with enough auspicious omens, one could achieve that exact effect in pure Lua, today:

local byte, reverse, gsub = import( 'string' )

print( byte, reverse, gsub )

Just requires a bit of, err, luck and, hmmm, lateral thinking :P

Implementation details left as an exercise to the interested reader.

(Hints bellow)






















Hint:

local function import( aName, aPrefix )
  local function Source()
    local aLine = debug.getinfo( 3, 'l' ).currentline
    local aSource = debug.getinfo( 3, 'S' ).source
    local aFile = io.open( aSource:sub( 2 ), 'r' )

    if aFile then
      local anIndex = 0

      for anIndex = 1, aLine - 1 do
        aFile:read( '*l' )
      end

      return aFile:read( '*l' )
    end
  end

  local aModule = require( aName )
  local aPrefix = aPrefix or ''
  local aSource = Source()
  local aList = {}

  for aKey in aSource:sub( aSource:find( 'local ' ) + 6, aSource:find( '=' ) - 1 ):gmatch( '([^,%s]+)' ) do
    aKey = aKey:sub( aPrefix:len() + 1 )
    aList[ #aList + 1 ] = assert( aModule[ aKey ], ( 'unknown key %q in module %q' ):format( aKey, aName ) )
  end

  return table.unpack( aList )
end