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

Variable isn't doubling [easy]

Started by bloodless2010, 05 October 2012 - 06:43 PM
bloodless2010 #1
Posted 05 October 2012 - 08:43 PM
My code just prints 1 over and over as the variable, when it should be doing 1 then 2, then 4, then 8,16,32,64,128, then back to 1,2,4,8,16 and so forth, over and over, but my "debug" style thing that prints the variable is just saying 1 and 1 and 1 when it should be 1,2,4,8,16,32,64,128 :/ It should be easy, thanks!
Here's my code;

local side = "back"
local num = 1

function s()
sleep(.2)
end

function glow()
if num < 128 then
local num = num + num
end

if num == 128 then
local num = 1
end

rs.setBundledOutput( side, num)
end

while true do
print(num)
s()
glow()
end
KaoS #2
Posted 05 October 2012 - 08:45 PM
just take out the local when you double it or that change only reflects in the function in which you double it
bloodless2010 #3
Posted 05 October 2012 - 08:47 PM
Ohhh! I didn't realise that.
Thank you so much! I was so used to using local in defining variables, thank you so much.
Orwell #4
Posted 05 October 2012 - 09:09 PM
You can do the doubling up to 128 simply by replacing:

if num < 128 then
  num = num + num
end
if num == 128 then
  num = 1
end

with:


num=(num*2)%256

EDIT: just noticed that you wan't it to start at zero, so this might need some modification :(/>/>
EDIT: just thought of this trick:

num = math.max(1, (num*2)%256)
Fatal_Exception #5
Posted 05 October 2012 - 11:48 PM
And then you step back and realize that you've just made the whole thing harder to read for no actual gain, and made it less efficient too.
Orwell #6
Posted 06 October 2012 - 12:17 AM
And then you step back and realize that you've just made the whole thing harder to read for no actual gain, and made it less efficient too.

I like short code, but if you want efficiency, use shift operators. >.< without the math.max, it's definitely more efficient. It's just unfortunate he doesn't want zero.
And if you go further on efficiency, 'num=num+num' requires more operations than 'num=num*2'. And that requires more operations than 'bit.blshift(num,2)'.
I was just trying to help there. If bloodless wants a hint that's more on the same road; you can use 'if … else … end' to make it more efficient/coherent.