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

How to count how many times an element appears in a table?

Asked by 3 years ago

Say that I have a table like this:

local table = {"1", "1", "2", "3", "4"}


for i,v in pairs(table) do
    print(v)
end

How would I go about creating a function that counts how many times each item is in the table? For example, it would return 2 for "1", but it would return 1 for the others. Thanks.

1 answer

Log in to vote
0
Answered by
kjljixx 42
3 years ago
Edited 3 years ago
local table={"1","1","2","3","4"}
local table_count
for i,v in pairs(table) do
    --adding the information from the original table to a count
    if not table_count[i] then
        table_count[i]=1
    else
        table_count[i]+=1
    end
end
--function that will return how many times an object is in the original table.
local function count_returner(identifier)
    if table_count[identifier] then
        return table_count[identifier]
    else
        --[[will return false since there are no instances of the item you are looking for. you can also change this to 0 if you like]]
        return false
    end
end

the above code will work but it is probably a "dumb" way; there are probably more straightforward solutions.

0
I think you're suppose to replace "i" with "v". ScuffedAI 435 — 3y
0
yeah, thanks for catching that kjljixx 42 — 3y
Ad

Answer this question