[NTLK] NewtonScript fun
Matthias Melcher
m.melcher at robowerk.de
Fri Aug 15 15:36:06 PDT 2025
As usual, some geek stuff from me.
I have been playing around with NewtonScript. It's a damn great language!
I am using C++ for most of my programming life, but it's not elegant by any means, it's complicated, full of rules with even more exceptions, and it has been expanded over recent years in ways that are not always - um - obvious. NewtonScript OTOH is a bit like Lua. It has very few rules. Those rules just set the outer perimiter, but within those rules, you can write very smart stuff.
So here is some random NewtonScript that you may understand, even if you don't speak the language. It's almost and English sentence. The indentatation is purely to make it better readable:
|IsThree: func(a) begin
| if a = 3 then
| return "three"
| else
| return "not three";
|end
Well, it's a function that returns a text depending on the value of a. If you then type "IsThree(5);", you would get "not three".
But NewtonScript is very flexible in its syntax. Note that = compares and := assigns (in C++, that would be == and = respectively). We can also write
|func(a) begin
| return if a = 3 then
| "three"
| else
| "not three";
|end
It does the same thing, but here, the entire if-then-else construct is is seen as an expression (a mathematical function if you will). Let's make it more convoluted ("&" connects text segments):
|func(a) begin
| return ( if a = 3 then
| ""
| else
| "not " ) & "three";
|end
Yes, this is all stuff I found in Apple example source code ;*)
Oh, and I just *have* to add this one. So let's write two functions to get the score of a soccer game:
|GetHomeScore: func() return hometeam.score;
|GetGuestScore: func() return guestteam.score;
Ok, let's put that in a single function (the tick in front of "home" means I literally mean the *home* team, not a team that may be called "Home" for some reason):
|GetScore: func(team) begin
| if team = 'home then
| return hometeam.score;
| else
| return guestteam.score;
|end
Also pretty clear. Now, since if-then-else is just an expression and not some extra construct, replacing "hometeam" with an "if" expression is legal. So we can actually write:
|GetScore: func(team) begin
| return if team = 'home then begin
| hometeam
| end else begin
| guestteam
| end.score;
|end
Yes, end.score is legal code. It took me five good looks until I understood this code. Depending on "team", it evaluates to "hometeam.score" or "guestteam.score". The "end" is just the end of the "if" expression.
I hope this excursion made at least two people on the list chuckle.
Still trying to convince you guys to write new software for the MessagePad. ;-)
- Matthias
More information about the NewtonTalk
mailing list