This topic contains 4 replies, has 3 voices, and was last updated by  Jeff Drumm 1 year, 10 months ago.

Test for presence of segment

  • I’m trying to build interface code that is flexible enough to handle multiple message types, and in some cases, one message type will have a segment that a different message type lacks. If I reference that missing segment, I get an error in the translator. Is there a way to test if a segment exists before I try to reference any part of it?

    -Robert James,
    Interface Analyst,
    GetWellNetwork, Inc.

    Assuming you’ve defined the segment as optional in the vmd, you can use the node.isNull() function to determine whether or not the segment exists in the message:

       if not msg.NK1:isNull() then
          -- handle the NK1
       else
          -- leave the empty NK1 alone
       end
    

    Jeff Drumm ◊ VP and COO ◊ HICG, LLC. ◊ http://www.hicgrp.com

    Thanks, Jeff. A question: do you know how this would behave is the segment header is there, but nothing else? For example we received just ‘NK1’ with nothing following it?

    -Robert James,
    Interface Analyst,
    GetWellNetwork, Inc.

    Hi Robert,
    Jeff’s solution works great if you have the segment defined in the message grammar of your vmd but it does not work if the segment is there but is blank. One way we have found to get around such limitations is to do it as string comparisons.

    function NodeExists(Data)
    	if Data == nil then return false end
    	if type(Data) ~= 'string' and tostring(Data):find('NK1') ~= nil and tostring(Data) ~= 'NK1|||||||' then return true 
    	elseif type(Data) == 'string' and Data:find('NK1') ~= nil and Data ~= 'NK1|||||||' then return true end
    	return false
    end

    Its a bit cumbersome but it works

    You’ll still be able to reference the fields within the segment without error, even though they’re empty or not present. For example:

        local kinLanguage = msg.NK1[1][20]:S()
    

    won’t return an error even if the NK1 segment exists but has no fields beyond some arbitrary count, or the fields are empty, such as:

    NK1|||

    In the above code snippet, parsing the example NK1, kinLanguage will be set to the empty string (”).

    Jeff Drumm ◊ VP and COO ◊ HICG, LLC. ◊ http://www.hicgrp.com

You must be logged in to reply to this topic.