[Date Prev][Date Next][Thread Prev][Thread Next]
[Date Index]
[Thread Index]
- Subject: Re: finding keys in a table
- From: "Alex Davies" <alex.mania@...>
- Date: Thu, 21 Feb 2008 23:34:12 +0900
Exactly as you list:
From: "Jelle Huisman" <jelle@jhnet.nl>
(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
else
tab[char] = 1 -- (2b) else add new entry
end
(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: http://www.lua.org/pil/3.3.html)
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 }
end
table.sort(reverse, function(a, b) a[2] < b[2] end)