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

Run a function again while it's still running

Started by TheShadowGamer, 25 June 2016 - 06:11 PM
TheShadowGamer #1
Posted 25 June 2016 - 08:11 PM
I'm making an elevator using railcraft with two carts. For now I'm working on the call button: a computer decides which elevator should be called; for now it check to see if a cart is idle and then calls that cart(If someone was to be using another elevator, it would not be called)
My setup:
http://imgur.com/vVZVymd

Calling an elevator works, the problem is that the reason there are two elevators and not one is so that multiple could be used at once: if someone was to call an elevator while one is running, it cannot be called until the other one is finished. I suppose I would need the same function to be called again while it's already running so the left elevator can operate at the same time.

Here is the code for the computer controlling when an elevator is called:
http://pastebin.com/AK0fwvE4

I am fairly new to LUA and computercraft but I understand basic programming concepts.
As you can probably guess, the right elevator will only ever get called while the left stays put. I am alright with this unless the right is currently in use.

I've been researching: would coroutines help me?
Emma #2
Posted 26 June 2016 - 02:23 AM
–snip–

So yeah, coroutines is the basic principle of this problem. However, they can be very confusing for people to lua. Fortunately, computercraft includes a very nice API called parallel. It allows you to give it a bunch of functions to run in 'parallel' (hence the name). It's not true parallel, but it works good enough for the scope of this post (If you would like to learn more about coroutines and their magic click here). The basic jist of what you need to do to work with the parallel api is to have two functions, one to listen and activate the left elevator, and one to listen and activate the right elevator, one each. Then all you have to do is this:

parallel.waitForAny(listenForLeftElevator, listenForRightElevator)
Also, a side note, if either of the functions exit/return then both will stop, to counter this either put the parallel.waitForAny in a while true loop or put the code inside the functions inside a while true loop.
This is what I mean:
Spoiler

function listenForLeftElevator()
  while true do
	--Listen and activate your left elevator
  end
end

function listenForRightElevator()
  while true do
	--Listen and activate your right elevator
  end
end

parallel.waitForAny(listenForLeftElevator, listenForRightElevator)
Edited on 26 June 2016 - 12:24 AM