lua-users home
lua-l archive

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



For those interested, here's the outcome of my 'local predeclarations' cry.

This approach allows both the using and target functions to be declared in the regular way. None of the metamethods are really necessary, they serve merely as a safety net agains mistyped (nil) values and such.

The '__call' method allows for "UPCALL( 'Loc_ShellCommand', cmd )" syntax, but I'm not very fond of that..

-ak


  --
local UPCALL= {} -- set of functions where we need out-of-scope access

  setmetatable( UPCALL,
    {
    __newindex= function( tbl, key, val )
if not val then error "Predeclaring to 'nil'.. are you mad?" end
                    rawset( tbl, key, val )
                end,
    --
__index= function( tbl, key ) -- only called when value was 'nil'
                    error( "Function not predefined: "..key )
                end,
    --
    __call=     function( tbl, name, ... )
local f= assert( tbl.name, "Function not predefined: "..name )
                    f( unpack(arg) )
                end
    } )

Usage:
	local function whatever()
		...
	  	UPCALL.Loc_ShellCommand( cmd )
		...
	end

Later:
  	local function Loc_ShellCommand( cmd )
		...
  	end
  	UPCALL.Loc_ShellCommand= assert( Loc_ShellCommand )