Scripting Helpers is winding down operations and is now read-only. More info→
Ad
Log in to vote
0

Do Functions NEED a Loop or do Functions have a Built-in Loop?

Asked by
woodengop 1134 Moderation Voter
9 years ago

In RBX.Lua are you able to Add Loops such as: Whiles/While true do, Repeat, For, etc.

Or Does functions have a Built-in Loop?

Please respect that I am a Beginner in need for Knowledge

2 answers

Log in to vote
1
Answered by 9 years ago

Of course you can add loops to a function! And no, functions don't have any 'built-in' loops.

When you call a function, it's scope [the code inside] will run like a regular script.

For example, let's look at a couple examples of code:

function consoleLog(txt)
print(txt)
end

consoleLog("Hi!")

The following code above will call the consoleLogfunction ONCE, and it will run only ONCE.

Now, what if you wanted the function to say 'Hi!' more than once? Perhaps 50 times.

We can use a for loop now!

function consoleLog(txt)
for i = 1,50 do
print(txt)
end
end

consoleLog("Hi!")

The code above will use the for loop as a way of iterating from 1 to 50. We can achieve the same paradigm using a while loop aswell.

function consoleLog(txt)
count = 0
while count < 50 do
count = count + 1
print(txt)
end
end

consoleLog("Hi!")

We can even use a 'repeat' conditional iterator

function consoleLog(txt)
count = 0
repeat
count = count + 1
print(txt)
until count == 50
end

consoleLog("Hi!")

As you can see, you can always add loops into a function. Functions don't have any 'built-in' loops because people don't always need loops, as shown in the first example.

If you're learning, this may help you: http://wiki.roblox.com/index.php/Absolute_beginner%27s_guide_to_scripting#Make_your_own_functions

2
For the loop, couldn't you just do print(string.rep("Hi!",50)) instead of looping it 50 times to reduce lag? EzraNehemiah_TF2 3552 — 9y
0
Are you serious? Did you even read what his question was? DigitalVeer 1473 — 9y
Ad
Log in to vote
1
Answered by 9 years ago

Functions do not require loops and if you wish to put a loop within a function you can just place your loop code within the function. In order to call a function, use an event and a call statement, a call statement being written as FunctionName(). If you have any other questions I would be glad to help.

Function with a while loop:

function loop()
    while wait() do
        print("Hello World")
    end
end

loop()

Function with a for loop:

function loop()
    for i = 1, 50 do
        print("Hello World")
        wait()
    end
end

loop()

Function with a repeat:

i = 0

function loop()
    repeat
        print("Hello World")
        i = i + 1
    until i == 10
end

loop()

Function called in-line on an event:

Workspace.Part.Touched:connect(function ()
    print("Hello World")
end

Function called on an event:

function touch()
    print("Hello World")
end

Workspace.Part.Touched:connect(touch)

Answer this question