attempt to index number with number at line 18? “if t[1] == passId then”
im trying to make a trail system via gamepasses.
Code:
local trails = {
[1] = {168076886, "Rainbow"},
[2] = {168077603, "Red"},
[3] = {168077473, "Green"},
[4] = {168077290, "Blue"},
}
local function func(plr, passId)
local char = plr.Character or plr.CharacterAdded:Wait()
if char.Head:FindFirstChild("Trail") then
char.Head["1"]:Destroy()
char.Head["2"]:Destroy()
char.Head["Trail"]:Destroy()
end
for t = 1, #trails do
print(t[1], passId)
if t[1] == passId then
local trail = game.ReplicatedStorage.Objects.Trails[t[2]]:Clone()
trail["1"].Parent = char.Head
trail["2"].Parent = char.Head
trail["Trail"].Parent = char.Head
end
end
end
game:GetService("MarketplaceService").PromptGamePassPurchaseFinished:Connect(function(...)
func(...)
end)
Simply, t is a number. You can fix this error by changing:
for t = 1, #trails do
To:
for _, t in trails do
Or, if you want to keep this same method, you can do this after that line:
for i = 1, #trails do
local t = trails[i] -- returns a table based on your current code
-- then the rest of the code goes here...
end
Hopefully that helps!
For a deeper explanation about "for-loops"
When you’re doing for loops, there are two ways of doing it.
The way that you are doing:
for v = min, max, inc do
...
end
Is an incremental loop (optionally can change inc) that continues until v is equivalent to max. It’s giving an error because v will ALWAYS be a number. So, in your case, v would be t. Which is why you’re producing the Attempt to index number with number error.
What I believe you meant to do is, loop through the table of trails. Which brings to the other way of making a for loop:
for k, v in [pairs/ipairs](t) do
...
end
Which basically loops through the given table (t) and returns the key (k) and value (v) for every item in the array. In your case, k would be the numbers that are within brackets inside trails and v would be the table that k stores.
Alternatively, you can still use the incremental for-loop for table iteration, as I’ve shown from before. The downside is, your keys would need to be in a numerical value that starts from the lowest keyNumber within your code. And if there isn’t a key with that EXACT number, it’ll throw an error, breaking up the loop and the rest of the code after it.
I didn’t even realise that i messed that up. Thank you both @edozune@bluebxrrybot it works now.
for i = 1, #trails do
if trails[i][1] == passId then
local trail = game.ReplicatedStorage.Objects.Trails[trails[i][2]]:Clone()
trail["1"].Parent = char.Head
trail["2"].Parent = char.Head
trail["Trail"].Parent = char.Head
end
end