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

[Lua] Negative Numbers and Centering Text

Started by Sirharry0077, 15 February 2013 - 12:56 PM
Sirharry0077 #1
Posted 15 February 2013 - 01:56 PM
I have been trying to create a function like the following that will center text and print it.


function center(text, xoffset, yoffset)
if xoffset == nil then xoffset = 0 end
if yoffset == nil then yoffset = 0 end
len = string.len(text)
len = math.ceil(len / 2)
local x,y = term.getSize()
x = math.ceil((x / 2) - len + xoffset)
y = math.ceil((y / 2) - len + yoffset)
term.setCursorPos(x, y)
print(text)
end
When I run it, it doesn't allways work correctly. Would giving it negative numbers affect it and is there a more efficient way to do this?
theoriginalbit #2
Posted 15 February 2013 - 02:09 PM
You have a bug in the y position calculation, see code below for the fix

local function center(text, xoffset, yoffset)
  xoffset = xoffset or 0 -- this is the same as if xoffset == nil then xoffset = 0 end
  yoffset = yoffset or 0
  local len = #text / 2
  local x,y = term.getSize()
  term.setCursorPos( math.floor( x/2 - len + xoffset), math.floor( y/2 + yoffset ) )
  write(text)
end

Also negative numbers would work fine since x + -1 would minus 1 from x