lua-users home
lua-l archive

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


On Apr 9, 2014, at 1:54 PM, steve donovan <steve.j.donovan@gmail.com> wrote:

> https://gist.github.com/stevedonovan/10259826
> 
> require 'from'
> local sin,cos,tan = slots(3) from(math)
> local import,printf = slots(2) from 'pl.utils'
> local pretty,utils,xml = slots(3) from 'pl.*’

Let the hack fest continue! :D

Yet another hack for your entertainment:

local upper, lower = import from( 'string' )

print( 'upper', upper, upper( 'a' ) )
print( 'lower', lower, lower( 'B' ) )

> upper	function: 0x1034049b0	A
> lower	function: 0x1034045d0	b


With prefix, just because:

local mmin, mmax = import from( 'math', 'm’ )

print( 'mmin', mmin, mmin( 1, 2 ) )
print( 'mmax', mmax, mmax( 1, 2 ) )

> mmin	function: 0x103402740	1
> mmax	function: 0x1034026d0	2


Implementation details left to the imagination… but see bellow if you really must...































local import = nil

local function from( aName, aPrefix )
  local aModule = require( aName )
  local aPrefix = aPrefix or ''
  local anIndex = 2

  while true do
    anIndex = anIndex + 1

    if debug.getlocal( 2, anIndex ) == nil then
      break
    end
  end

  for anIndex = anIndex - 1, 1, -1 do
    local aName, aValue = debug.getlocal( 2, anIndex )
    local aKey = aName:sub( aPrefix:len() + 1 )

    if aModule[ aKey ] == nil or aValue ~= nil then
      break
    end

    debug.setlocal( 2, anIndex, aModule[ aKey ] )
  end
end

local upper, lower = import from( 'string' )

print( 'upper', upper, upper( 'a' ) )
print( 'lower', lower, lower( 'B' ) )

local mmin, mmax = import from( 'math', 'm' )

print( 'mmin', mmin, mmin( 1, 2 ) )
print( 'mmax', mmax, mmax( 1, 2 ) )