Say you wanted to store everything you print into a table. You'd make a function along these lines:
local buffer = {}
local function bufferPrint(text)
local curx,cury = term.getCursorPos()
if buffer[cury] then -- If we've already got some text stored for this line, then...
if #buffer[cury] < curx then -- If that saved text doesn't reach the current column, then...
buffer[cury] = buffer[cury]..string.rep(" ",curx-#buffer[cury]-1)..text
else -- Otherwise the saved text must reach the current column, perhaps exceeding the new text length.
buffer[cury] = buffer[cury]:sub(1,curx-1)..text..buffer[cury]:sub(curx+#text,#buffer[cury])
end
else -- There's no text in the buffer for this line.
buffer[cury] = string.rep(" ",curx-1)..text
end
term.write(text)
term.setCursorPos(1,cury+1)
end
There are a few ways I can think of off the top of my head that'll break this (scrolling for eg), and I haven't tested it (so don't be surprised if it's buggy), but hopefully it at least gets the general idea across. You could really devote an entire API to doing this properly (eg, handling colour, multiple buffered pages, word-wrap and scrolling, maybe making the function accept co-ords so you don't ever have to call "term.setCursorPos()" separately, etc…).
A few points you may not be familiar with:
"if buffer[cury] then" will treat "buffer[cury]" as "true" if it has a value, or false if it doesn't.
"#buffer[cury]" gets the length of whatever text is in "buffer[cury]".
"string.rep(" ",x)" returns a string which consists of x amount of spaces (it repeats a given string however many times - a space, in this case).
"buffer[cury]:sub(x,y)" returns a sub-string of buffer[cury], starting at character x and ending at character y. So if "buffer[cury]" contains the string "cabbage", and you get "buffer[cury]:sub(4,6)", the result is a string stating "bag".
If you're not familiar with any of the "term" functions, I recommend reviewing the appropriate
wiki articles.
Anyway, say you use this function to draw your display (using "bufferPrint" instead of regular "print"), then go off and use regular writing functions for anything you don't want saved. You can then later restore what you buffered like this:
local function restoreBuffer()
term.clear()
for i=1,table.maxn(buffer) do -- "table.maxn(buffer)" returns the highest index number in the "buffer" table.
if buffer[i] then
term.setCursorPos(1,i)
term.write(buffer[i])
end
end
end
Or write it to a file using something like this:
local function saveBuffer(fileName)
local myFile = fs.open(fileName,"w")
for i=1,table.maxn(buffer) do
if buffer[i] then
myFile.writeLine(buffer[i])
else
myFile.writeLine("")
end
end
myFile.close()
end