Search code examples
lualoadlua-5.2

Is there a way to catch the output in lua?


I'm trying to catch the output from for example: print('Hello') and store it in a variable / table.

Please let me know if this is even possible. If not thanks for answering.


Solution

  • You can't intercept standard output directly, but you can change the global print function:

    local outputs = {}
    local function storeOutputs(...)
      table.insert(outputs, {...})
    end
    
    local oldPrint = print
    function print(...)
      storeOutputs(...)
      oldPrint(...)
    end
    

    I'm not sure if there's a way to deal with io.write calls.