←  APIs and Utilities

ComputerCraft | Programmable Computers for Minecraft

»

Function to write string in enclosed space

oli414's Photo oli414 20 Jun 2015

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 by oli414, 20 June 2015 - 04:49 PM.
Quote

Creator's Photo Creator 20 Jun 2015

Thank you. This can be used in any text editor!
Quote

Dahknee's Photo Dahknee 30 Jun 2015

edit: Doesn't do what I wanted :( Cool wordwrap though!
Edited by DannySMc, 30 June 2015 - 02:35 PM.
Quote