Format data using repeating fields or segments

Verified
Added by iNTERFACEWARE

How to format a report as a single NTE or OBX segment with repeating field or using multiple NTE segments, one for each line of the report

Source Code
-- this code follows best practice of using local functions
-- this requires that main() is placed at the end of the file
-- after the local functions

local Report = "Patient's head appeared to be potatoe shaped.\nSpoke of needing to get back to the other\ntoys and mentioned Woody."

local UseOneNte = true

local function Split(str, delim, maxNb)
   -- Eliminate bad cases...
   if string.find(str, delim) == nil then
      return { str }
   end
   if maxNb == nil or maxNb < 1 then
      maxNb = 0    -- No limit
   end
   local result = {}
   local pat = "(.-)" .. delim .. "()"
   local nb = 0
   local lastPos
   for part, pos in string.gfind(str, pat) do
      nb = nb + 1
      result[nb] = part
      lastPos = pos
      if nb == maxNb then break end
   end
   -- Handle the last field
   if nb ~= maxNb then
      result[nb + 1] = string.sub(str, lastPos)
   end
   return result
end

function main(Data)
   local Out = hl7.message{vmd='example/demo.vmd', name='Lab'}
   local Lines = Split(Report, "\n")
   print("There are "..#Lines.." lines in the report.")
   
   if (UseOneNte) then
      for i=1, #Lines do
         Out.NTE[1][3][i] = Lines[i]   
      end
   else 
      for i=1, #Lines do
         Out.NTE[i][3][1] = Lines[i]   
      end
   end
   Out:S()
end
Description
How to format a report as a single NTE or OBX segment with repeating field or using multiple NTE segments, one for each line of the report
Usage Details

This is a very common problem in HL7. Some systems expect textual reports to be formatted into a single OBX or NTE segment with a repeating field, while others want each line of the report in its own NTE segment.

This code sample demonstrates how simple it is to achieve both options. To switch between options just set the UseOneNte flag to “true” or “false”.

How to use the code:

  • Paste the code into a script
  • Inspect the code and annotations to see how it works
  • Change the UseOneNte flag from “true” to “false” to switch between modes