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

Bumping a new centering function

Started by Lemmmy, 17 January 2016 - 12:29 AM
Lemmmy #1
Posted 17 January 2016 - 01:29 AM
no!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
Edited on 13 February 2016 - 04:53 PM
HPWebcamAble #2
Posted 17 January 2016 - 02:05 AM
This is the one I usually use, I think I've got it centering correctly:


local w,h = term.getSize()

local function printC(text,y)
  if type(text) ~= "string" or type(y) ~= "number" then error("expected string,number, got "..type(text)..","..type(y),2) end
  local lenght = #text
  local start = math.floor((w-lenght)/2)+1
  term.setCursorPos(start,y)
  term.write(text)
  return start,start+lenght
end

It returns the starting x position and the ending x position of the text, in case you need them.
Pyuu #3
Posted 17 January 2016 - 02:06 AM
Instead of checking if text is a string, just do tostring(text).
Dragon53535 #4
Posted 17 January 2016 - 02:09 AM
It's a function that can be used in an api and not confuse the user.
Pyuu #5
Posted 17 January 2016 - 02:11 AM
The only reason why it seems too far centered to the left is because of the size of the screen. Math.floor is applied to all decimal values regarding text placement.
Bomb Bloke #6
Posted 17 January 2016 - 02:46 AM
Look, I get that you guys are having fun with your "let's make the board index show up with all the same avatar" thing, but let's still keep posts at least somewhat intelligent. Some of this stuff is bordering on spam.

The correct formula is to subtract the width of the string from the width of the display, halve and then floor the result, and then - because the first text column is one - add one.

No, there's absolutely no need to run through and bump a bunch of threads with this basic bit of math, if that's what you're asking.