mudgangster

Log | Files | Refs

alias.lua (1957B)


      1 local Aliases = { }
      2 
      3 local function doAlias( line )
      4 	local command, args = line:match( "^%s*(%S+)%s*(.*)$" )
      5 	local alias = Aliases[ command ]
      6 
      7 	if alias and alias.enabled then
      8 		local badSyntax = true
      9 
     10 		for i = 1, #alias.callbacks do
     11 			local callback = alias.callbacks[ i ]
     12 			local ok, err, subs = pcall( string.gsub, args, callback.pattern, callback.callback )
     13 
     14 			if not ok then
     15 				mud.print( debug.traceback( "\n#s> alias callback failed: %s" % err ) )
     16 
     17 				return true
     18 			end
     19 
     20 			if subs ~= 0 then
     21 				badSyntax = false
     22 
     23 				break
     24 			end
     25 		end
     26 
     27 		if badSyntax then
     28 			mud.print( "\nsyntax: %s %s" % { command, alias.syntax } )
     29 		end
     30 
     31 		return true
     32 	end
     33 
     34 	return false
     35 end
     36 
     37 local function simpleAlias( callback, disabled )
     38 	return {
     39 		callbacks = {
     40 			{
     41 				pattern = "^(.*)$",
     42 				callback = callback,
     43 			},
     44 		},
     45 
     46 		enabled = not disabled,
     47 
     48 		enable = function( self )
     49 			self.enabled = true
     50 		end,
     51 		disable = function( self )
     52 			self.enabled = false
     53 		end,
     54 	}
     55 end
     56 
     57 local function patternAlias( callbacks, syntax, disabled )
     58 	local alias = {
     59 		callbacks = { },
     60 		syntax = syntax,
     61 
     62 		enabled = not disabled,
     63 
     64 		enable = function( self )
     65 			self.enabled = true
     66 		end,
     67 		disable = function( self )
     68 			self.enabled = false
     69 		end,
     70 	}
     71 
     72 	for pattern, callback in pairs( callbacks ) do
     73 		table.insert( alias.callbacks, {
     74 			pattern = pattern,
     75 			callback = callback,
     76 		} )
     77 	end
     78 
     79 	return alias
     80 end
     81 
     82 function mud.alias( command, handler, ... )
     83 	enforce( command, "command", "string" )
     84 	enforce( handler, "handler", "function", "string", "table" )
     85 
     86 	assert( not Aliases[ command ], "alias `%s' already registered" % command )
     87 
     88 	if type( handler ) == "string" then
     89 		local command = handler
     90 
     91 		handler = function( args )
     92 			mud.input( command % args )
     93 		end
     94 	end
     95 
     96 	local alias = type( handler ) == "function"
     97 		and simpleAlias( handler, ... ) 
     98 		or patternAlias( handler, ... )
     99 	
    100 	Aliases[ command ] = alias
    101 
    102 	return alias
    103 end
    104 
    105 return {
    106 	doAlias = doAlias,
    107 }