How do scripts work

for example

local e = false
game:GetService("UserInputService").InputBegan:Connect(function(Input)
       if Input.KeyCode == Enum.KeyCode.E then
            e = true

            while wait() do
                   if e == true then
                   print ("printing")
      end
end

game:GetService("UserInputService").InputEnded:Connect(function(Input)
       if Input.KeyCode == Enum.KeyCode.E then
            E = false
      end
end

while wait() do
print("hi")
end

it starts printing hi when the game starts but when i press e it starts printing both simultaneously

but i thought you can only run one function in a time in a way?

1 Like

In your specific case, I believe that when you “press” e, it starts the while wait() loop for both the InputBegan, and also the while wait() loop at the bottom. They don’t run at the same time, but the time in between frames is so small that it appears that way.

Also, if you’re trying to make the loop stop, you might need to correct your script below. local e = false is not the same as E as Lua accounts for case, so it might result in an error.

I might be missing something but are you using a different variable accidentally?

“e = true”

On the InputEnded, you use a capital “E” instead of a lowercase “e”, different variables maybe, unless I’m just missing it.

I may be wrong, its late and I’m tired but that was the first thing I saw, or I’m just missing something.

oh dont mind that im just giving an example.

1 Like

Alright at least I didn’t miss it but it was just an example, as he said.

That’s fine. Either way, my previous point should still stand. They aren’t technically running at the same time but because they are both while wait() loops, they happen very quickly one after the other.

but is it true that u can only run like one function at a time i guess?

You’ve put:

while wait() do
print(“hi”)
end

At the end, this will run separately to the functions and will continuously print “hi”.

As for how it works, functions, only one coroutine can be run at a time, Roblox just switches between each coroutine very quickly.

Edit:

Roblox does this because, Lua is single threaded. The task scheduler will run each function sequentially (one by one), but not at the same time.

2 Likes

See what @Axiomatikos said. Roblox only runs one function at a time, but because of the way that the script is set up it “feels” like they’re both running simultaneously.

Scripts in Roblox work differently than your standard “top-to-bottom” style you see when you code most things.

For instance, your code will run through all the way until the while wait() loop and won’t go further even if you add something after it (unless you break the loop).

The InputBegan and InputEnded things you are using are Events. They will run regardless if your script is running below, even if it is currently in a loop. Think of an event as a mini script that runs when an event occurs.