Lua SDK - split() function behaves unexpectedly with zero length fields
search cancel

Lua SDK - split() function behaves unexpectedly with zero length fields

book

Article ID: 281646

calendar_today

Updated On: 04-04-2024

Products

DX Unified Infrastructure Management (Nimsoft / UIM)

Issue/Introduction

I am trying to use the Lua SDK's "split()" function to parse a list of comma-separated values.

However, when there are two commas in a row (e.g. an empty field) this is not being captured appropriately.

 
For example, consider the following string of comma-separated values:
 
myString = "a,b,c"
 
If we pass this to split() as follows, with comma defined as the separator:
 
myTable = split(myString, ",")
 
The result is a table of strings as follows:
 
{"a", "b", "c"}
 
 
But if you pass a string like:
 
myString = "a,,c"
 
Then you get:
{"a", "c"}

 

Why doesn't it capture the empty field, and return  {'a", "", "c"} ?

 

 

Cause

Working as designed

Resolution

The documentation for split() says:

 

split ( String [, Separators ])
Returns a table of substrings separated by one or more of the Separator characters. The default separator is whitespace.

 

The key here is "one or more" - multiple separator characters are essentially ignored/combined into a single one.

So from the point of view of the split() function, the following are all equivalent:

"a,b"
"a,,b"
"a,,,,,,,,,,,,,,b"

All of these will return  {"a","b"}

As are:

"a,b,c"
"a,,b,,c"
"a,,,,,b,,,,,,,,,,,,,,,,,,,,,,,,,,,c"

All of these will return {"a","b","c"} 

 

Additional Information

No workaround is available but an Idea has been posted to enhance the split() function to allow for zero-length fields:

https://community.broadcom.com/idea/uim-lua-sdk-split-function-behaves-unexpectedly-with-zero-length-fields