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

How to center text

Started by nikolay04, 09 November 2016 - 06:11 PM
nikolay04 #1
Posted 09 November 2016 - 07:11 PM
I got challenged to make a file managment system. And i need to know how to make the text centered. So i need to know how to do this Thanks
Bomb Bloke #2
Posted 11 November 2016 - 03:14 AM
The general math is simple: take the length of the text from the width of the screen, halve then floor the result, and finally, as Lua is 1-indexed, add one.

local function centerWrite(text)
  local x, y = term.getCursorPos()
  term.setCursorPos(math.floor((x - #text) / 2) + 1, y)
  term.write(text)
end
Exerro #3
Posted 11 November 2016 - 07:37 PM
The general math is simple: take the length of the text from the width of the screen, halve then floor the result, and finally, as Lua is 1-indexed, add one.

local function centerWrite(text)
  local x, y = term.getCursorPos()
  term.setCursorPos(math.floor((x - #text) / 2) + 1, y)
  term.write(text)
end

I think you missed something in the code:

local function centerWrite(text)
  local x, y = term.getCursorPos()
  local w, h = term.getSize() --# get the width/height of the screen
  term.setCursorPos(math.floor((w - #text) / 2) + 1, y) --# subtract x from the width, not the current cursor x
  term.write(text)
end

Depending on how you want evenly wide text to be drawn, you might want to add one to `w - #text` (`w - #text + 1`). If the text is 2 wide, the screen width is 51, so the position it is drawn at will be floor((51-2)/2)+1 = 25 (slightly to the left of the centre). By adding one, you'll get floor((51-2+1)/2)+1 = 26 (slightly to the right of the centre), and oddly wide text will still be perfectly central.
Edited on 11 November 2016 - 06:37 PM
Bomb Bloke #4
Posted 12 November 2016 - 12:52 AM
Shows how much sleep I've been getting lately… That was a bad one. :wacko:/>
jakejakey #5
Posted 13 November 2016 - 02:06 PM
Here is a centering function

local function center(str,ln)
  local maxX,maxY = term.getSize()
  term.setCursorPos((maxX/2)-(#str/2),ln)
  print(str)
end
center("Testing",2)
With that, you should just be able to specify the line to print to, and then you are set