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

quick one (functions)

Started by Dustmuz, 25 February 2015 - 12:42 AM
Dustmuz #1
Posted 25 February 2015 - 01:42 AM
can you change a variable in Function A with function B
using global variables for this, in hopes of it will be working



function center (text)
  x, y = mon.getSize()
  x1, y1 = mon.getCursorPos()
  mon.setCursorPos((math.floor(x/2) - (math.floor(#text/2))+1), y1)
  mon.write(text)
  mon.setCursorPos(x1,y1+1)
end

function space()
 y1=y1+1
end
KingofGamesYami #2
Posted 25 February 2015 - 01:45 AM
That would not work, because y1 is set at the time you call center(text). Therefore space() will change the variable to one greater than itself, and center will promptly override that change.

The proper way of doing this would go something like this:

local yOffset = 0

function center( text )
  local x, y = mon.getSize()
  local x1, y1 = mon.getCursorPos()
  y1 = y1 + yOffset
  mon.setCursorPos( (math.floor( x/2 ) - (math.floor( #text/2))+1), y1 )
  mon.write( text )
  mon.setCurosrPos( x1, y1 + 1 )
end

function space()
  yOffset = yOffset + 1
end
Dustmuz #3
Posted 25 February 2015 - 01:48 AM
okay thanks a lot King.. no wonder i couldnt get it to work :P/> hehe
Quintuple Agent #4
Posted 25 February 2015 - 01:48 AM
Well, yes since y1 is a global variable, y1 would be shared between the 2 functions, however since 'center' sets y1 to the cursors y pos at the start of the function, it would not make a difference what it is changed to.
Also, Instead of it being global to the entire computer, you could just make it local to the script

local y1
function stuff()
--code
y1=y1+4
end
function test()
y1=y1-31
end

Edit: Curses! Sniped again!
Edited on 25 February 2015 - 12:49 AM