lua-users home
lua-l archive

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


On Nov 17, 2013, at 8:46 AM, Sir Pogsalot <sir.pogsalot@gmail.com> wrote:

> (please be constructive, I know this is a topic for bad criticism in some circles)

BAD! BAD! BAD! Ok, now that’s out of the way, let the hack fest begin! :D

Two devious hacks for your consideration:


(1) (ab)use _ENV

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

print( min, min( 1, 2 ) )
print( max, max( 1, 2 ) )
print( math )

—8<—
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
—>8—


(2) (ab)use locals

local min, max = nil; import( 'math' );

print( min, min( 1, 2 ) )
print( max, max( 1, 2 ) )


—8<—
local function import( aName )
  local aModule = require( aName )
  local anIndex = 0
  local aList = {}

  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 )

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

    debug.setlocal( 2, anIndex, aModule[ aName ] )
  end
end
—>8—

All these weird and delightful ways to shoot oneself in the foot! yeah!