lua-users home
lua-l archive

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


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... ?