Function Tag.getTagValue

Lookup a child tag by name, and retrieve a value of type T from it. Returns a default value if not found.

Useful if you only expect one value of type T from a given tag. Only looks for immediate child tags of this, doesn't search recursively.

This is a shortcut for getTag().getValue(), except if the tag isn't found, then instead of a null reference error, it will return the requested defaultValue (or T.init by default).

Prototype

T getTagValue(T)(
  string fullTagName,
  T defaultValue = T.init
)
if (isValueType!T);

Example

import std.exception;
import sdlang.parser;

auto root = parseSource(`
	foo 1 "a" 2 "b"
	foo 3 "c" 4 "d"  // getTagValue considers this to override the first foo
	
	bar "hi"
	bar 379  // getTagValue considers this to override the first bar
`);
assert( root.getTagValue!int("foo") == 3 );
assert( root.getTagValue!string("foo") == "c" );

// Value found, default value ignored.
assert( root.getTagValue!int("foo", 999) == 3 );

// Tag not found
// If you'd prefer an exception, use `expectTagValue` instead.
assert( root.getTagValue!int("doesnt-exist", 999) == 999 );
assert( root.getTagValue!int("doesnt-exist") == 0 );

// The last "bar" tag doesn't have an int (only the first "bar" tag does)
assert( root.getTagValue!string("bar", "Default") == "Default" );
assert( root.getTagValue!string("bar") is null );

// Using namespaces:
root = parseSource(`
	ns1:foo 1 "a" 2 "b"
	ns1:foo 3 "c" 4 "d"
	ns2:foo 11 "aa" 22 "bb"
	ns2:foo 33 "cc" 44 "dd"
	
	ns1:bar "hi"
	ns1:bar 379  // getTagValue considers this to override the first bar
`);
assert( root.getTagValue!int("ns1:foo") == 3  );
assert( root.getTagValue!int("*:foo"  ) == 33 ); // Search all namespaces

assert( root.getTagValue!string("ns1:foo") == "c"  );
assert( root.getTagValue!string("*:foo"  ) == "cc" ); // Search all namespaces

// The last "bar" tag doesn't have a string (only the first "bar" tag does)
assert( root.getTagValue!string("*:bar", "Default") == "Default" );
assert( root.getTagValue!string("*:bar") is null );

Authors

Copyright

License