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

Color Changing Monitor

Started by HVENetworks, 06 May 2018 - 05:45 AM
HVENetworks #1
Posted 06 May 2018 - 07:45 AM
I am trying to make a program which will display black until the monitor is clicked, and turn into blue. Like a light switch.

local cmon = peripheral.wrap("top")
local state = 0


while true do
  if state==1 then
    cmon.setBackgroundColor(colors.blue)
    cmon.clear()
  else
    cmon.setBackgroundColor(colors.black)
    cmon.clear()
  end
  event, side, x,y = os.pullEvent()
  if event == "monitor_touch" then
    if state==0 then
      local state = 1
    end
    if state==1 then
      local state = 0
    end
  end
end
Stekeblad #2
Posted 08 May 2018 - 07:24 AM

 if state==0 then
    local state = 1
 end
 if state==1 then
    local state = 0
 end
Two thins I see in this section:
1. You are creating a new "state" variable that only exist inside the if blocks, remove local part in this section.

2. State will always be 0. If state is zero you set it to 1 and then check if it is one and change it back to 0. Instead of
if…end if…end
Change to like
if…elseif…end
This way only one of the if section will be run every itteration of the loop.

All the code at the top could also just be exchanged by one line and get the same result:

state = (state + 1) % 2
HVENetworks #3
Posted 08 May 2018 - 01:30 PM
I'm really new to this, and haven't done anything in Lua before either
Stekeblad #4
Posted 09 May 2018 - 06:37 AM
Try changing the code section from my last post i your code to look lile this

 if state==0 then
    state = 1
 elseif state==1 then
    state = 0
 end
Edited on 09 May 2018 - 04:38 AM