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

[Help] How Do I Center Text

Started by IPandaI, 21 January 2017 - 10:07 PM
IPandaI #1
Posted 21 January 2017 - 11:07 PM
The title says it all but i want to center a print("Welcome back")
Dog #2
Posted 22 January 2017 - 12:04 AM
I'm going to guess that you're asking about centering the text horizontally. To do that, simply subtract the width of the text from the width of the terminal window and divide the result by two. To ensure a whole number result use math.floor() or math.ceil() to round down or up.

local termX, termY = term.getSize()
local text = "Welcome Back"
term.setCursorPos(math.floor((termX - #text) / 2), 1)
term.write(text)

EDIT: The concept for vertical centering is pretty much the same. You take the height of the terminal and subtract half the number of lines in your text (so if your text was one line you'd subtract zero, and if it were two lines you'd subtract one, etc. - note that with odd numbers you can round up or down depending on your centering preference - I tend to round down), then divide that result by two. Then apply math.floor() or math.ceil() to round down or up to the nearest whole number.

local termX, termY = term.getSize()
local text = "Welcome Back"
term.setCursorPos(1, math.floor(termY / 2))
term.write(text)

You can combine the two methods to center both horizontally and vertically.
Edited on 21 January 2017 - 11:40 PM