Hi, so I have a table, which has four numbers (1,2,3, and 4, respectively) and I need to add all of them together, but the thing is that I don’t know how I would do that, the result should be 10, but I don’t know how to do that, if you can help me than thanks!
By the way, I only need a very little snippet of code
Something like this?
local Numtable = {["1"] = 1;
["2"] = 2;
["3"] = 3;
["4"] = 4;
}
local count = 0
for _, Number in pairs(Numtable) do
count += Number
return count
end
Okay, for
It says:
Assigning 1 values to 2 variables initialises extra variables within nil; add nil to value to silence
And for
It says:
Expected ‘=‘ when parsing assignment, got ‘in’
Mind sending the script you’re using so I could take a look and see what exactly you’re attempting to accomplish?
Also, tiny error in my own snippet of code, sorry about that! The code/method below should work now.
Revised Snippet (Sorry!)
local Numtable = {["1"] = 1;
["2"] = 2;
["3"] = 3;
["4"] = 4;
}
local count = 0
for _, Number in pairs(Numtable) do
count += Number
end
print(count)
Sorry, it was my error, I forgot to add a space between for
and _,
so it calulated it as a Variable, I have to test the Script
and I’ll tell you if it works
You don’t need the [""] things:
local numTable = {1, 2, 3, 4}
local count = 0
for _, Number in pairs(numTable) do
count += Number
end
print(count)
It’s working now! I tried it 3 times and it worked! It always printed the right result! Thanks!
True, but it’s easier to image if you have it in Dictionary format as opposed to an array!
Also, no worries, let me know if you need any more help or it errors at all!
Depends on how the OP obtained the table. What if it was passed through other scripts? A long list of table with those values as indexes would be inefficient…
It downs error, now I only have one problem which I’m researching right now, if you can help me, how to add a value to a table, yes, I really need help with tables, I’ll tell you if I find anything
Edit: I just found I have to use table.Insert
You’re right, I just used a Dictionary to help him better imagine it as a direct correlation between the index (ie. [“1”]) to the value he wanted to extract (ie. the integer “1”)!
Again, though, you’re absolutely right. It’s much more efficient to pass down an array as opposed to a dictionary through other scripts, although I do think it’s overall negligible how much efficiency will be lost unless done in extreme amounts.
This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.