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
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!
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.