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

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

Asked by
porw2 6
6 years ago

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

Log in to vote
2
Answered by
BlueTaslem 18071 Moderation Voter Administrator Community Moderator Super Administrator
6 years ago
Edited 6 years ago

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.

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! porw2 6 — 6y
Ad

Answer this question