Here is something that caught me out. Here are a series of simple programs that test the different way buffers can be tested if empty. The first case gives an error when testiing b == null Buffer b = create b = ""
if (b == null) { delete b
-R-E- DXL: <Line:5> null buffer parameter was passed into argument position 2
The next case gives an error when testing if b == "" b = ""
if (b == "") { delete b
-E- DXL: <Line:5> incorrect arguments for (==)
In the next case because null is a function, people might try this. However it gives no result, an incorrect answer, but no error. This is a trap because the condition is never true if b is empty. b = ""
if (null(b)) { delete b No error, does not print anything
But this works. In this case try testing for !null(b). The correct answer is printed if b is not empty. b = "1"
if (!null(b)) { delete b prints Hello
However this is the correct solution, working for empty and non empty Buffers. b = ""
if (stringOf b == null) { delete b prints Hello
Recorded here for posterity and because it is not documented elsewhere. ADent - Wed Nov 18 03:55:30 EST 2015 |
Re: Correct Way to Test for Empty Buffer I would test the emptiness of a buffer using:
Buffer buf = create();
if (length buf == 0) {
print "Empty";
}
Since the buffer stores its length, this is a very fast operation. Note that using (stringOf b) will produce a string that will be persisted in the string table, and therefore leak memory. This is especially relevant when using this function on very large buffers. Note that a null buffer should be treated like an error, so I would normally not do something like: if (null buf || length buf == 0) { ... } Regards, Mathias |