lua-users home
lua-l archive

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


Alex Davies wrote:
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)

actually,

    tab[char] = (count or 0) + 1

is slower than

    if count then
        tab[char] = count + 1
    else
        tab[char] = 1
    end

(the if then variant takes 60% of the time of the or case; the interpreter needs an extra LOADK)

in a similar fashion, parallel assignments can be faster

Hans

-----------------------------------------------------------------
                                          Hans Hagen | PRAGMA ADE
              Ridderstraat 27 | 8061 GH Hasselt | The Netherlands
     tel: 038 477 53 69 | fax: 038 477 53 74 | www.pragma-ade.com
                                             | www.pragma-pod.nl
-----------------------------------------------------------------