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

Redstone Powered RNG

Started by BuffetBarbarian, 14 December 2012 - 11:49 AM
BuffetBarbarian #1
Posted 14 December 2012 - 12:49 PM
Hello all, I come to you today with a question that I know should be easier than I'm making it out to be. I am new to working with Lua, and am trying my hand at making a rather simple (in function) program. It just seems to hate me.
I want to make a program that does this:
1.Wait for a redstone input from a specific side (back, for instance)
2.Generate a single random number
3.Create a pulse specific to the number (for example, 1 creates a pulse on the right side, 2 on the back, etc)
4.Wait for a redstone input again.

The code I have so far is:

repeat
if redstone.getInput("back",true) then
  i=math.random(1,3)
  if i==1 then
   redstone.setOutput("left",true)
   sleep(0.5)
   redstone.setOutput("left",false)
   end
  if i==2 then
   redstone.setOutput("right",true)
   sleep(0.5)
   redstone.setOutput("right",false)
   end
  if i==3 then
   redstone.setOutput("front",true)
   sleep(0.5)
   redstone.setOutput("front",false)
   end
end
until a
But this cancels itself out after a moment, giving me the error "Too long without yielding," or it gives me a massive supply of random pulses.
Help?
Cranium #2
Posted 14 December 2012 - 01:00 PM
On this line:

if redstone.getInput("back",true) then
Replace it with these two lines:

local event, p1 = os.pullEvent()
if event == "redstone" and rs.getInput("back") then
It will wait for any input on the back side, and prevent the error you are getting.
theoriginalbit #3
Posted 14 December 2012 - 01:22 PM
But this cancels itself out after a moment, giving me the error "Too long without yielding," or it gives me a massive supply of random pulses.
Help?

The reason you are getting "Too long without yielding" is because the main repeat loop it sees as an infinite loop when that if condition doesn't fire and terminates it, if you add a sleep(0.1) or some other small value it won't terminate with that error and it will still run.

Also if you wish this is how I would do it:

This makes it extremely versatile. To add more output sides all you would do is add a new string into the outputSides table and the code would do the rest, instead of having to make more if statements etc. If you have any questions about this, just ask :)/>

outputSides = { "left", "right", "front" }

repeat

if rs.getInput("back") then
  i = math.floor(math.random() % #outputSides)
  rs.setOutput(outputSides[i], true)
  sleep(0.5)
  rs.setOutput(outputSides[i], false)
end


until a