lua-users home
lua-l archive

Re: Most efficient way to recognize a line by its first (up to) three characters

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


It was thus said that the Great meino.cramer@gmx.de once stated:
> 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... ?
 local prefix = serialport:read(1)
 if prefix == ONE_CHAR_PREFIX then
 local data = serialport:read(based-on-prefix)
 else
 prefix2 = serialport:read(1)
 -- now, use prefix and prefix2 to determine if you have
 -- all the data, or if you need to read one more byte
 end
 -spc

AltStyle によって変換されたページ (->オリジナル) /