I want to add all of the indexes together, without rewriting the code every time I add something new.
It prints 15 times 1
local t = {
v
}
for key,value in pairs(t) do
key = num
print(key)
end
I want to add all of the indexes together, without rewriting the code every time I add something new.
It prints 15 times 1
local t = {
v
}
for key,value in pairs(t) do
key = num
print(key)
end
I am a little bit confused by what you mean, but heres my best interpretation of what you mean?
local array = {31,32,33,34,35,36}
local num = 0
for i,v in pairs(array) do
num += i
end
print(num) -- outputs 21
Hopefully this helps, if not please clarify a little bit better about what you mean.
@anythingoliver Hi I could have just printed the indexes got 15 and inserted 15 into a variable.
But that’s not how games work at least the good ones, I need efficient code so that I won’t rewrite every single script.
I need to add all of the indexes together in order to make this work.
Thank you for at least replying to my post, most people scroll down.
I’m still confused by what you mean “add all the indexes together in order to make this work”.
can’t you just add a break after the key = num ?
It prints 1 (x15)
how do I add all of them
Thanks for reply, I tried break but that’s not the case everything prints perfectly if I break it then it will stop that’s not the reason.
If I understand correctly, you want something like this?
local YourTable = {"1", "2", "5", "5"}
local TrackNumbers = {}
for _, value in ipairs(YourTable) do
if not TrackNumbers[value] then
print(value)
TrackNumbers[value] = true
end
end
Why not just get the number of items in the array? You can do #Array to return the number of items inside the array.
Same thing like table right?
I mean the script thingy.
prints 1 (15x)
Well, if you do print(#t) you will get 15 printed according to the code you provided.
To be honest I have no idea what you’re trying to acomplish, so some more details would be much appreciated (Like the actual table you’re trying to do this on, an example, etc)
But looking at the title, you can do this like so:
local total = 0
local testTable = {
"fun",
"fun2",
"fun3",
"fun4",
"fun5"
}
for key, value in pairs(testTable) do
total += key
end
print(#testTable) -- This prints out the total number of entries in the table (5)
print(total) -- This prints out the sum of every entry (15)
If this doesn’t work, then whatever you’re trying to achieve might not be possible.
What do you mean by this?‍‍‍‍‍‍‍‍‍
Instead of looping through, just take your Table Variable and prefix it with “#”.
Example:
local MyTable = {
"Hello",
"AnotherString"
}
print(#MyTable)
-- prints 2
If you add a new thing to the table, it will continue to go up in numbers. Note this only works if your indexes start at 1 and are in order.
This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.