Is there a function that allows counting of values within a table?

So I’ve got a table which essentially has duplicate entries, ie;



1 = Adzter
2 = Adzter
3 = Adzter
4 = John
5 = James
6 = Adzter


However I’m struggling to find a way to count how many instances there are of each value. I’ve looked all over the net and have gotten no-where. Is there no count by value function that i’m missing?

There’s no standard library feature to do this, just create another table to keep track of entries already iterated over, if it’s already been iterated over don’t increase the count, else increase it.

Is it mysql or sql?
If yes, SELECT COUNT FROM TABLE WHERE ( KEY = VALUE );

We’re in a GMod Lua forum… :v:

I was aiming for the opposite actually, essentially it’s a vote system. The player selects one player and presses ‘vote’, this name is then sent to the server and put into a table. I’m now trying to count how many times each player is in the table. I can’t find a viable way of doing so however. Any help would be much appreciated.

You should use the player as a key.

[lua]local votes = {}
local function voteFor(ply)
votes[ply] = ( votes[ply] or 0 ) + 1
end

local function countVotes(ply)
return votes[ply]
end[/lua]

That seems to have done the trick for counting how many votes the player has. Thanks a lot for your help! As a final quick question, to find the value that is highest would it be a simple case of SortByMember?

even simpler, just table.sort will do!

table.sort doesn’t seem to sort as expected, after running the function and printing the table there seems to be no change:

http://puu.sh/5XEJH.png

-snip-

-snip- look below

You won’t be able to sort your data in to a non-numerically-indexed table (such as string indexes) as lua does not store the order of these in any way.
You could instead have a numerically-indexed table that contains tables containing the players and their values and sort it with table.SortByMember



tab = {
    {Player = ply1, Value = 15},
    {Player = ply2, Value = 10},
    {Player = ply3, Value = 25}
}

table.SortByMember(tab, "Value")


EvacX’ solution below looks like it’d get you the output you want. This is still a nice way to sort it if you had wanted that.

Sorting is totally useless on non-numerical indices.



local max = 0

for k, v in pairs( stuff ) do
    if v > max then max = v end
end


Use table.GetWinningKey instead of sorting it.

It’s “sorting” it anyway. https://github.com/garrynewman/garrysmod/blob/master/garrysmod/lua/includes/extensions/table.lua#L679-L693