This is a read-only snapshot of the ComputerCraft forums, taken in April 2020.
oli414's profile picture

Function to write string in enclosed space

Started by oli414, 20 June 2015 - 03:45 PM
oli414 #1
Posted 20 June 2015 - 05:45 PM
Hey everyone,

I was messing around with Computercraft and needed a function to write a string in a box but wanted to make sure that the text wouldn't go outside of this box,
So I created this simple function that will automatically add enters to prevent it from going outside of it's predetermined area.
Thought that it wouldn't hurt sharing.
Let's say that you've got a string: "The quick brown fox jumpes over the lazy dog named SUPERAMAZINGUBERDOG!"
and want it to be in a 10 characters wide space, than it'll write:

The quick
brown fox
jumpes
over the
lazy dog
named SUPE
RAMAZINGUB
ERDOG!



function writeEnclosed(x, y, text, width)
term.setCursorPos(x, y)
local linePos = 0
local line = 0
for word in text:gmatch("%w+") do
  if word:len() <= width - linePos then
   term.setCursorPos(x + linePos, y + line)
   term.write(word)
   linePos = linePos + word:len()
  elseif word:len() > width then
   local seperated = {}
   for i = 1, word:len() do
	term.setCursorPos(x + linePos, y + line)
	term.write(word:sub(i, i))
	linePos = linePos + 1
	if linePos >= width then
	 line = line + 1
	 linePos = 0
	end
   end
  else
   linePos = 0
   line = line + 1
   term.setCursorPos(x + linePos, y + line)
   term.write(word)
   linePos = linePos + word:len()
  end
  if linePos < width then
   term.write(" ")
   linePos = linePos + 1
  end
end
end

Feel free to use this if you ever need this function

-Oli414
Edited on 20 June 2015 - 03:49 PM
Creator #2
Posted 20 June 2015 - 05:46 PM
Thank you. This can be used in any text editor!
DannySMc #3
Posted 30 June 2015 - 03:18 PM
edit: Doesn't do what I wanted :(/> Cool wordwrap though!
Edited on 30 June 2015 - 01:35 PM