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

Simple Changing Variable

Started by Remove, 01 April 2014 - 02:16 PM
Remove #1
Posted 01 April 2014 - 04:16 PM
I'm trying to make a simple program to be able to input a value between 0 and 15, and the computer then output a redstone signal strength equal to that number. I don't know how to keep the variable stored so that the signal remains active until another variable is input to change it to a different value of 1-15. So, it would accept the input, then ask for another one in order to change it. This would be the only program running on the computer. I can set up the display for it myself, I just know it can be a lot more compact than me doing 16 lines of "while i = X do".

Thank you for the help.
Lyqyd #2
Posted 01 April 2014 - 05:49 PM
All you have to do is set the redstone output. It's reasonably simple to program this:


--# get initial arguments:
local args = {...}
local side
local strength

local function printUsage()
  print("Usage:")
  print(fs.getName(shell.getRunningProgram()).." <side> [strength]")
end

if #args < 1 then
  --# they didn't give the side name
  printUsage()
  return
else
  --# verify that the side is a real side
  for _, s in pairs(rs.getSides()) do
    if args[1] == s then
      side = args[1]
      break
    end
  end
  if not side then
    --# provided side was not correct
    error("Invalid Side!", 0)
  end
end

if #args == 2 then
  --# they also have an initial strength, let's use it.
  strength = tonumber(args[2])
end

--# start the main body of the program
while true do
  if strength then
    --# if statement ensures we only set the output when strength is a valid number, because it is always tonumber()'d.
    rs.setAnalogOutput(side, strength)
  end
  print("Signal Strength?")
  write("> ")
  --# tonumber ensures that strength will always be nil or a valid number
  strength = tonumber(read())
end

I don't usually just give code as an answer. Please be sure to read through and take the time to understand the code and what it does.