-- build a word tree (character occurrence tree) and walk it pairs = {} wordTree = {} wordTreeP = wordTree function p(m, s) if s ~= nil then for i = 1, s:len() do local c = s:sub(i, i) if c >= "a" and c <= "z" or c >= "A" and c <= "Z" then local n = wordTreeP[c] if n == nil then n = {} wordTreeP[c] = n end wordTreeP = n else wordTreeP = wordTree end end end local c, n = next(wordTreeP) return c end