TestExpr
A function added by the New Vegas Script Extender.
Contents
Description
TestExpr is passed any expression and returns True (1) if it succeeds, or False (0) if it fails; meaning it generates an NVSE Error, and the error message is suppressed from appearing in the console.
This is an alternative to validating one's data, which might require multiple lines. Essentially it is saying; "I know this line of code might fail, so tell me if it does and I will handle it. In this case the 'error' is normal, so don't alert the user".
Comparable to the 'try', 'catch/except' found in some programming languages. Added by NVSE 4.1.
Syntax
(Result:bool) TestExpr AnyLine:expression
Example
Simple example, instead of bothering to check a key exists with Ar_HasKey:
if TestExpr SomeArray[SomeKey] ; SomeArray has SomeKey else ; SomeArray does not have SomeKey, but don't show an error about that. endif
The advantage that testexpr has over other validity checks is that the expression is actually performed inside the check if it can be. Suppose you want to keep a tally of the number of times the player encounters every NPC of a particular name:
array_var aTally ref rActor string_var actor_name let aTally := Ar_Construct "stringmap" ; ... let actor_name := $rActor if TestExpr aTally[actor_name] += 1 ; do nothing. The increment worked because the actor_name is in the array already else let aTally[actor_name] := 1 ; * first time we met actor_name, so create the entry endif
Rather than 'do nothing' if testexpr returns true, consider only doing something if it returns false:
if 0 == testexpr aTalley[actor_name] += 1 ; if "actor_name" is a valid key, the actual increase already happens here let aTalley[actor_name] := 1 endif
Suppose you are worried a ref variable might be empty for some reason, so your functions would fail:
ref rActor int iStrengthStat if TestExpr iStrengthStat := rActor.GetAV "Strength" ; do nothing. The function worked, so rActor must be valid else ; rActor isn't valid, so don't proceed further yet return endif
TestExpr's return of a bool telling you if the expression succeeded or not doesn't mean that you can only use it in an if-condition:
let iKey := ar_size aSomeArray while -1 < (iKey -= 1) testexpr ar_erase aSomeArray[iKey][2], 3 ; if [2][3] exists for any aSomeArray[iKey], will do the erasure. If not, then not. loop
Notes
- Variables can be assigned using ':=', '+=', etc, using any NVSE aware command (such as TestExpr, Eval, While...), not just with Let.