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

What is the meaning of "i" as stated bellow?

I'm not really new to scripting, but i'm not all that good at it. If anyone can tell me what the "i"'s function is, please tell me. Here's an example i found in an old script i had laying around:

or i=1,#disasters do
	local item = game.Lighting:findFirstChild(disasters[i])
	if item ~= nil then
		item.Parent = nil
		table.insert(items, item)
	else
		print("Error! ", disasters[i], " was not found!")
	end

(Note that "i" is located at the end of sentence 2, in case you missed it.)

1 answer

✓ Accepted answer

for loops let you do something "for each" element in some collection.

The "numeric" for loops, like those seen here, count. They look like this:

for myCounter = smallest, largest do

This for statement introduces the variable myCounter. The loop will execute over and over with new values for myCounter:

  • myCounter is smallest
  • myCounter is smallest + 1
  • myCounter is smallest + 2
  • myCounter is smallest + 3
  • ...
  • myCounter is largest - 1
  • myCounter is largest

In your example, the variable is just called i which is a typical abbreviation for "index".

It starts at 1 and ends at #disasters, which is the number of disasters. Thus the loop executes one for each disaster;

  • i is 1 and disasters[i] is disasters[1], the first disaster
  • i is 2 and disasters[i] is disasters[2], the second disaster
  • i is 3 and disasters[i] is disasters[3], the third disaster
  • ...
  • i is #disasters and disasters[#disasters] is the final disaster

When you have a loop that looks like the one you have and you repeatedly use disasters[i] it's pretty clear that the i doesn't really have a meaning, and you'd really just get at each disaster.

You can use a generic for loop, one with an ipairs iterator generator, to do this:

for _, disaster in ipairs(disasters) do
	local item = game.Lighting:FindFirstChild(disaster)
	......

You should use :FindFirstChild. The lowercase version :findFirstChild is deprecated.

You should store objects in ServerStorage or ReplicatedStorage, not in Lighting.

1 comment

0

This was some old script someone made that i had left in one of my old places that i made before they introduced ServerStorage. Hence why they where stored in Lighting. I was just wandering what it's("i") use was. And now i know, and became even smarter! thx!

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