InputBegan/Ended Problem

Hello, I have issue with InputBegan and InputEnded.

My code:

All of this works fine, up until I release the key, aka InputEnded.

The output states the InputBegan runs after the InputEnded has run, and I don’t know why.

Any help is appreciated.

1 Like

Sometimes, when code is ran fast, 2 strips of code run at almost the same time, producing this error, so you basically stopped the input in between the first and the second heartbeat, this happens almost all the time.

1 Like

It is because of the RSH:Wait() part. As it is, :Wait() will yield the thread for a frame, meaning it will run after it is done even if the key was released during this time. Place the RSH:Wait() at the loop’s end and it should work.

3 Likes

@nooneisback I didn’t know that, thanks for the help!

1 Like

@VegetationBush Thanks for the reply., I’ll continue to take that in mind when I continue editing code. Thanks for the help!

One thing to note is that 2 lines cannot run at the same time. Here’s an example.

local coro = coroutine.create(function() --creates a separate thread
    print("separate thread started")
    coroutine.yield() --yields this thread
    print("separate thread done")
end)

coroutine.resume(coro) --starts the separate thread
print("main thread running")
coroutine.resume(coro) --resumes the yielded thread

-> separate thread started
-> main thread running
-> separate thread done

The separate thread will run before the main thread because it was resumed then; however, adding a wait changes the output order. This is because the separate thread isn’t running, meaning the main thread can be resumed.

local coro = coroutine.create(function() --creates a separate thread
    wait() --yields the main thread. It runs before print("main thread running"), but pauses, giving it a green flag to continue
    print("separate thread started")
    print("separate thread done")
end)

coroutine.resume(coro) --starts the seaparte thread
print("main thread running")

-> main thread running
-> separate thread started
-> separate thread done

In short, no matter how complex a function is, unless you order it to yield using wait or coroutine.yield() it will run for as long as it hasn’t reached its end or return.

1 Like

@nooneisback Yea, I’m running into a problem where when I am pressing one key, and press another, the construct becomes laggy, and sometimes it takes time to respond to another press. Any idea how to fix this? I have very little knowledge of coroutines.

If there is nothing outside this block that causes the lag, I’d imagine that replacing the while loop with an event connection might help a bit, but I’m not sure what might be causing that.

Keep the connection variables outside the began keybind and disable them on ended.

1 Like

Alright I’ll do that, thanks for the help!