lua-users home
lua-l archive

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


Am 11.03.2014 20:27, schrieb Luiz Henrique de Figueiredo:
Bottom line: you need to describe your input precisely. After that, it'll
be simple to adapt the ideas given in this thread to handle each line.


Putting all above together is fun (and the result may or may not fit):

local function printf(frm, ...)
  print(string.format(frm, ...))
end

local function adapt_handler(prefix_len, LHF_handler)
  return function(line)
     local prefix = line:sub(1,prefix_len)
     local info   = line:sub(prefix_len+1)
     return LHF_handler(prefix, info)
  end
end

local frm = "prefix='%s', info=:'%s'";

local handlers={
    ["A;"]  = function(prefix, info) printf(frm, prefix, info) end,
    ["AB;"] = function(prefix, info) printf(frm, prefix, info) end,
    ["ABC;"]= function(prefix, info) printf(frm, prefix, info) end,
    ["*A "] = function(prefix, info) printf(frm, prefix, info) end,
}

local adapted_handlers = {}
for k,v in pairs(handlers) do
  adapted_handlers[k] = adapt_handler(#k, v)
end

local badprefix=function (line) error("cannot handle "..line) end

example = [[
A;0000;0000;0000
AB;0000;0000;0000
ABC;0000;0000;0000
*A N
]]

for line in example:gmatch("[^\r\n]+") do
  local h =  adapted_handlers[line:sub(1,4)]
          or adapted_handlers[line:sub(1,3)]
          or adapted_handlers[line:sub(1,2)]
          or adapted_handlers[line:sub(1,1)]
          or badprefix
    h(line)
end


Prints out:
prefix='A;', info=:'0000;0000;0000  '
prefix='AB;', info=:'0000;0000;0000'
prefix='ABC;', info=:'0000;0000;0000 '
prefix='*A ', info=:'N'