lua-users home
lua-l archive

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]

Exactly as you list:

From: "Jelle Huisman" <>
(1) lookup if the current character already exists as a key in the table.
(2a) If it does exist I increment the value for key currentchar with 1
(2b) else I add a new entry: currentchar=1
(3) Later I sort the table and print my freq.list.

if tab[char] ~= nil then  -- (1) is the char in the table?
 tab[char] = tab[char] + 1  -- (2a) then increment
 tab[char] = 1  -- (2b) else add new entry

(It could also be written like this, for a bit more speed: )
local count = tab[char]
tab[char] = (count or 0) + 1 -- initializes count if necessary (an explanation can be found at:

Because you can't sort key/value pairs, sorting is a little bit more complicated:

local reverse = {}
for k,v in pairs(tab) do
 reverse[#reverse+1] = { k, v }
table.sort(reverse, function(a, b) a[2] < b[2] end)