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]


On Tuesday, March 11, 2014 08:12:49 PM meino.cramer@gmx.de wrote:
> ...and the problem with examples is, that they are examples only :)
> And I have to sent all variations to completly define what I need
> (which I am not allowed to do, by the way).
> Only to describe another variation:
> 
> *A N
> 
 codetree = {
 ['A'] = { function(str) --[[ handle A ]] end,
 ['AB'] = { function(str) --[[ handle AB ]] end,
 ['ABC'] = function(str) --[[ handle ABC ]] end
 }
 },
 ['*'] = { --[[ no handler for * ]]
 ['*A'] = function(str) print[[ handle *A ]] end
 }
 }
 function handlecode(str)
 local tree = codetree
 for p = 1,#str do
 local code = str:sub(1,p)
 local nextstate = tree[code] or tree[1]
 if type(nextstate) == "function" then -- leaf node
 return nextstate(str)
 elseif type(nextstate) == "table" then -- branch node
 tree = nextstate
 else
 print("Unknown code")
 return
 end
 end
 if tree[1] then
 return tree[1](str)
 else
 print("Unknown code")
 end
 end
You say you're concerned about the memory of a lookup table so if necessary 
you can prune leaves so the leaf functions have to handle multiple codes. And 
of course the tree can be constructed from a simple table of code=function 
pairs.
-- 
tom <telliamed@whoopdedo.org>

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