This is the first of my Cool Language Feature of the Arbitrary Time Period pieces, covering a particular snippet of Shiro code that shows off something it does neatly. The snippet goes up on the Google Code Home Page first (a lame reward for those who visit I guess), and once I decide to replace it with a new one, I blog about the old one. How bloody exciting...</deadpan>
So the previous snippet was a short one, but a good one,
def getp(o, propName is String){
return o~('.' + propName)
}
thing = {name: "bob", age: 27}
print getp(thing, "name")
This is about the simplest way to show off one of my favorite Shiro operators, that squiggly thing. It's called the Execution Operator (although I usually just say exec-op) and what it does it insert dynamic stuff into the token stream (ie: your source code) each time it's encountered. It literally lets you make dynamic Shiro and just run it whenever, wherever, however. And because of how it's implemented, you take only a minimal performance hit no matter what context you use it in, so it's basically a "free" operator.
In case you're not following, the getp method above returns an object's property by name. It could have just accessed it using array/tuple notation, but that wouldn't be any fun at all, so instead we build a '.<property>' string and just thrust it into the source code, right after a name. Shiro inserts the .<property> part and is now happy with the syntax, so it returns the value. Easy as that. The crazy thing about the operator is that it can appear literally anywhere, and as long as inserting the value of the result creates valid Shiro, it will run.
There are two different ways you can use this operator in Shiro. If you follow the tilde with a name only, it will insert the value of that variable into the token stream. If, as in the example above, you follow it with a parenthesis, it will evaluate the expression inside the parenthesis, then insert that into the token stream.
How this little gem differs from the ParamOp is worthy of a small chapter in the Quick Start Guide, but it will probably show up in a CLFATP one of these years.
No comments:
Post a Comment