Jump to content




Function to write string in enclosed space


2 replies to this topic

#1 oli414

  • Members
  • 29 posts
  • LocationThe Netherlands

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


#2 Creator

    Mad Dash Victor

  • Members
  • 2,168 posts
  • LocationYou will never find me, muhahahahahaha

Posted 20 June 2015 - 04:46 PM

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

#3 DannySMc

  • Members
  • 1,808 posts
  • Location/home/dannysmc95

Posted 30 June 2015 - 02:18 PM

edit: Doesn't do what I wanted :( Cool wordwrap though!

Edited by DannySMc, 30 June 2015 - 02:35 PM.






1 user(s) are reading this topic

0 members, 1 guests, 0 anonymous users