Scripting HelpersARCHIVE
A little piece of Roblox history. Preserved for everyone, one question at a time.Read about the archive →
✓ ANSWER ACCEPTED

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

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

✓ Accepted answer

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 consoleLog function 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 comments

2

For the loop, couldn't you just do print(string.rep("Hi!",50)) instead of looping it 50 times to reduce lag?

0

Are you serious? Did you even read what his question was?

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)

This discussion is preserved as it was. New answers, comments, and votes are closed.