[Date Prev][Date Next][Thread Prev][Thread Next]
[Date Index]
[Thread Index]
- Subject: Re: Most efficient way to recognize a line by its first (up to) three characters
- From: meino.cramer@...
- Date: Tue, 11 Mar 2014 19:25:00 +0100
Luiz Henrique de Figueiredo <lhf@tecgraf.puc-rio.br> [14-03-11 19:16]:
> > local prefix, info = line:sub(1,3), line:sub(4)
> > if prefix == "abc" then
> > -- do something
> > elseif prefix == "123" then
> > -- do something else
> > elseif ...
>
> Consider this scheme instead of a chain of ifs:
>
> local handlers={
> ["abc"]=function (prefix,info) ... end,
> ["123"]=function (prefix,info) ... end,
> }
>
> local badprefix=function (prefix,info) error("cannot handle "..prefix) end
>
> while true do
> local prefix, info = line:sub(1,3), line:sub(4)
> local h = handlers[prefix] or badprefix
> h(prefix,info)
> end
>
...whow!...
But how can I handle different length of prefixes with directly
following data... ?