Skip to main content

Overriding a Default Datatype with %Set() or %Push()

Overriding a Default Datatype with %Set() or %Push()

By default, the system automatically interprets a %Set() or %Push() value argument as an object datatype (object, array, or oref) or an ObjectScript literal datatype (string or number). You can not directly pass JSON literals null, true or false as values because the argument is interpreted as an ObjectScript literal or expression. For example, the following code throws an error because the value true is interpreted as a variable name:

   do o.%Set("prop3",true)

DO o.%Set("prop3",true)
^
<UNDEFINED> *true

ObjectScript uses "" (an empty string) for null, 0 for boolean false, and a non-zero number for boolean true. To deal with this problem, %Set() and %Push() take an optional third argument to specify the datatype of the value. The third argument can be JSON boolean or null. For example:

   write {}.%Set("a",(2-4)).%Set("b",0).%Set("c","").%ToJSON()
{"a":-2,"b":0,"c":""}

   write {}.%Set("a",(2-4),"boolean").%Set("b",0,"boolean").%Set("c","","null").%ToJSON()
{"a":true,"b":false,"c":null}

The third argument can also be string or number if the value could be interpreted as a number:

   write [].%Push("023"_"04").%Push(5*5).%ToJSON()
["02304",25]

   write [].%Push(("023"_"04"),"number").%Push((5*5),"string").%ToJSON()
[2304,"25"]
FeedbackOpens in a new tab