Espen

Synchronized Terminal Redirection POC

Mar 28th, 2012
179
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Lua 2.23 KB | None | 0 0
  1.  
  2. native = term.native or term
  3.  
  4. local redirectTarget = native
  5. local tRedirectStack = {}
  6. local bSyncScreens    -- Determines if I/O is to be synchronized over all objects (monitors and/or the terminal) in the stack.
  7. local bRedirectDims    -- Determines if the dimensions of the last redirect target take precedence over all other objects (monitors and/or the terminal).
  8.  
  9. -- true: Synchronizes I/O over all screens.
  10. -- false or nil: Only last active screen has I/O interaction.
  11. function syncScreens( bSync )
  12.   bSyncScreens = bSync
  13. end
  14.  
  15. -- true: Dimensions of the last object (monitor) in the stack take precedence.
  16. -- false or nil: Dimensions of 'native' (terminal) take precedence.
  17. function redirectDims( bRedirect )
  18.   bRedirectDims = bRedirect
  19. end
  20.  
  21. local function syncedTarget( _sFunction, ... )
  22.   if #tRedirectStack > 0 and not bRedirectDims then redirectTarget[ _sFunction ]( ... ) end
  23.     -- Execute the function call on every object (e.g. monitors) in the stack.
  24.     for i = #tRedirectStack, 2, -1 do    -- We skip the oldest element in the stack, because that will always be 'native' and we'll return that at the end directly.
  25.       tRedirectStack[i][ _sFunction ]( ... )    -- Execute the function call on the current object in the stack.
  26.     end
  27.    
  28.     if not bRedirectDims then
  29.       return native[ _sFunction ]
  30.     else
  31.       native[ _sFunction ]( ... )
  32.       return redirectTarget[ _sFunction ]
  33.     end
  34. end
  35.  
  36. local function wrap( _sFunction )
  37.     return function( ... )
  38.         if bSyncScreens then
  39.           return syncedTarget( _sFunction, ... )( ... )    -- Sync Screen behaviour.
  40.         else
  41.           return redirectTarget[ _sFunction ]( ... )    -- Native behaviour.
  42.         end
  43.     end
  44. end
  45.  
  46. local term = {}
  47. term.redirect = function( _object )
  48.     tRedirectStack[#tRedirectStack + 1] = redirectTarget
  49.     redirectTarget = _object
  50. end
  51. term.restore = function()
  52.     if #tRedirectStack > 0 then
  53.         redirectTarget = tRedirectStack[#tRedirectStack]
  54.         tRedirectStack[#tRedirectStack] = nil
  55.     end
  56. end
  57. for k,v in pairs( native ) do
  58.     if type( k ) == "string" and type( v ) == "function" then
  59.         if term[k] == nil then
  60.             term[k] = wrap( k )
  61.         end
  62.     end
  63. end
  64.    
  65. local env = getfenv()
  66. for k,v in pairs( term ) do
  67.     env[k] = v
  68. end
Advertisement
Add Comment
Please, Sign In to add comment