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

Help with index?

Asked by 10 years ago

I was wondering why is line 12 printing "nil" when I do line 13 it prints there name,why and how do I fix it?

Items = {"Bob","Tod","Josh"}
    function ChangedParts()
        ChangedItems = {}
            for i,v in pairs (Items) do
                local Part = Instance.new("Part",workspace)
                Part.Name = "New"..tostring(v)
            ChangedItems[v] = Part
            end
            return ChangedItems
    end
        Parts = ChangedParts()
        print(Parts[1])--nil?
        for i,v in pairs (Parts) do
            print(v)
        end

2 answers

Log in to vote
1
Answered by
Perci1 4988 Trusted Moderation Voter Community Moderator
10 years ago

v is the current value from the table, and i is the current index. When you have a table followed by brackets, inside those brackets must be a number. It has to be a number because it takes that number and gives you the value from the table corresponding with that number. Therefore when you do ChangedItems[v] = Part on line 07, it won't work because you are putting a value inside the brackets instead of a number.

ChangedItems[i] = Part

This should work, since i is the current index. However, the best way to add a value to a table would be to use table.insert().

table.insert(ChangedItems,Part)

Hope I helped!

1
In short, you saved the new part as "Bob", "Tod", and "Josh". You are looking for "1". That's why it's nill. GoldenPhysics 474 — 10y
0
I only did this way because I heard it's the easiest way to store single instances :p kevinnight45 550 — 10y
Ad
Log in to vote
-2
Answered by 10 years ago

No idea what went wrong but it prints nil because nothing's in "Parts." If you get the length of the table through #Parts, it shows up as 0.

Answer this question