TweetFollow Us on Twitter

Learn F-Script in 20 Minutes

Volume Number: 23 (2007)
Issue Number: 05
Column Tag: Programming

Learn F-Script in 20 Minutes

And have fun playing with Core Image

By Philippe Mougin

Welcome

If you are a Cocoa programmer chances are that you've heard of F-Script, an open-source scripting layer dedicated to Cocoa. If you haven't tried it yet, this is your chance to learn how it can improve your productivity as well as those of the users of your own Cocoa applications. In this article, our goal will be to produce a nice little animation using fancy Core Image effects. In doing so, we will learn the basics of F-Script. So install yourself comfortably in front of your Mac, download the latest F-Script version from http://www.fscript.org and enjoy the trip!

First Contacts

We are going to learn F-Script by taking advantage of one of its key functionalities: the ability to be used interactively. With its console, you can interactively type commands in order to manipulate Objective-C objects on the fly. The F-Script console opens automatically when you launch F-Script.app. Inside it, you can type F-Script expressions or scripts and have them immediately executed when you press Return.


Figure 1. The F-Script console, waiting for your input

F-Script is a Smalltalk dialect for Cocoa and should look very familiar to you. Indeed, Brad Cox, who created objective-C describes it as "a hybrid language that contains all of C language plus major parts of Smalltalk". Here is an example of a message sending expression, both in Objective-C and F-Script. In this example, we ask for the current date using the NSDate class provided by Cocoa.

Objective-C F-Script (i.e., Smalltalk)
[NSDate date] NSDate date

As you can see, the expression is similar, except for the fact that, in F-Script, you don't have to put brackets around your message. This is because F-Script is a very simple language and sending a message is nearly the only thing you can do. Therefore, there is no need to have a special syntax to delimit messages. Now, if you type this expression in the console and hit Return, it will be immediately evaluated and the result will be displayed (obviously, the result you'll get will differ from the one shown below):

> NSDate date
2007-03-16 17:01:45 +0100

F-Script provides numerous tools to assist you during such interactive Cocoa sessions. In this first session, you are likely to find the following tips useful:

The console keeps a history of your commands. You can navigate it using the up and down arrows of your keyboard. For instance, if you mistype something and F-Script signals an error, you can use this feature to get back at your command without having to retype it.

You can insert a line break by pressing the Enter key (usually found on the numeric keypad) or by pressing Return while holding the Control key.

The console also provides a code completion mechanism that you can use by pressing the F5 key. You can then navigate between arguments placeholders with Control-Slash.

A graphical object browser opens automatically at startup. It is a very powerful tool with which you can explore objects and send them messages.

Before continuing to talk about the language itself, let me give you a little bit of the history: Smalltalk was created in the early seventies at the famous Xerox Palo Alto Research Center, the PARC, by a team led by Alan Kay. As you might know, since then, Smalltalk has been having a big influence on the software industry. For instance, you might have heard about a visit that Steve Jobs made at the PARC in 1979. A visit that had a considerable influence on the design of the Lisa and the Macintosh computers. What Steve Jobs was shown there was Smalltalk. It had a graphical interface, was the first object-oriented system, and supported networking. "You guys are sitting on a gold mine here. Why aren't you making this a product?" asked the young Steve Jobs. A short time later, several people from the PARC were working at Apple and the rest is history...

So, what is the basic concept of Smalltalk? The key insight leading to the design of Smalltalk is that we can describe everything in terms of objects. As Alan Kay puts it "Smalltalk's design is due to the insight that everything we can describe can be represented by the recursive composition of a single kind of behavioral building block that hides its combination of state and process inside itself and can be dealt with only through the exchange of messages". Indeed, in Smalltalk, everything is an object, even numbersnumbers, or booleansBooleans.

It is also important to note that F-Script provides an interactive environment with which you can directly interact with your objects, instead of having to develop a specific application each time you want to do something.

F-Script's Syntax

In a F-Script program the main control structure is message sending. In F-Script, as well as in Objective-C, a message with no argument is called a "unary message". A message with one or more colons in its selector is called a "keyword message". And, unlike Objective-C, there is a third kind of message in F-Script: a message that is composed of non-alphabetical characters like +, -, etc., is called a "binary message". A binary message always has only one argument.

Message type Objective-C F-Script
Unary [NSDate date] NSDate date
Keyword [NSDate dateWithTimeIntervalSinceNow:10] NSDate dateWithTimeIntervalSinceNow:10
Binary Not available date1 < date2

The Objective-C equivalent to date1 < date2 would be [date1 compare:date2] == NSOrderedDescending.

As in Objective-C, messages can be chained together. Expressions are evaluated from left to right, giving us the same semantics, as shown below.

Objective-C F-Script (i.e., Smalltalk)
[[NSDate date]
timeIntervalSinceNow]
NSDate date timeIntervalSinceNow

But sometimes, we need a way to determine the order of evaluation of messages. F-Script introduces a precedence rule (the only precedence rule in the language): unary messages are evaluated first, then binary messages, and then keyword messages. If you want to change the order of evaluation, you can use parenthesis to delimit a message.

The following example shows a few other differences between F-Script and Objective-C:

Objective-C F-Script (i.e., Smalltalk)
NSDate *date1 =
[NSDate date];
date1 := NSDate date.

As you see, there is no type declaration in F-Script. Everything is an object and variable need not be explicitly typed. The assignment syntax uses := instead of just = in Objective-C, and the instruction separator is not the semicolon, but the period symbol, like in English sentences. The following table shows other differences. As you can see, strings are enclosed in single quotes, and comments are enclosed in double quotes.

 
Objective-C F-Script
@"A string" 'a string'
/* A comment */ "A comment"
@selector(dateWithTimeIntervalSinceNow:) #dateWithTimeIntervalSinceNow:
[NSMutableArray arrayWithObjects:@"Hi", @"mom", nil] {'Hi', 'mom'}
NSMakePoint(200, 80) 200<>80

Displaying a picture on screen

We now know enough of F-Script to begin with our Core Image program. We will first create an NSURL object referring to the image we want to display. In this exampleexample, we will use an image that is stored on disk in the desktop picture folder. You can type the code below in the F-Script console to have it executed immediately.

imageLocation := NSURL fileURLWithPath:'
/Library/Desktop Pictures/Nature/Clown Fish.jpg'.

The imageLocation variable now points to our NSURL object. We will now create a CIImage object, initialized with our image on-disk.

image := CIImage imageWithContentsOfURL:imageLocation.

Note that we are using standard methods provided by the Mac OS X frameworks. Now that we have an image object, we can ask it to draw itself on screen, again using a standard method.

image drawInRect:(200<>80 extent:300<>200) 
fromRect:image extent operation:NSCompositeSourceOver fraction:1.

After executing this code, we should see a beautiful little image displayed in the console, as shown below.


Figure 2. Loading and displaying an image using Core Image and F-Script

The first argument passed to the drawing method is the rectangle we want to draw in, which is denoted with 200<>80 extent:300<>200. This expression actually creates an NSValue object representing a rectangle with an origin at (200, 80), a width of 300 and a height of 200. When passed to the method, the NSValue is automatically mapped by F-Script to an NSRect structure. This kind of automatic mapping between objects and primitives Objective-C types makes it possible to use the Mac OS X Objective-C based frameworks from a pure object language such as F-Script. You can change the rectangle size to make the image bigger or smaller and immediately see the result on-screen.

The drawing method draws the image in the current graphic context, which, in our example, happens to be the F-Script console. It is possible, of course, to draw elsewhere, using standard Mac OS X techniques.

Using core image filters

Core Image filters allow us to do all kind of highly optimized image processing. Mac OS X comes bundled with dozens of filters. Going forward with our exploration, we will apply a filter known as CIBumpDistortion, which creates a bump in the image. You are encouraged to try other filters as well. F-Script's interactivity makes it fun and efficient to explore such Mac OS X capabilities. The following F-Script code creates a CIBumpDistortion filter object and configures it to process our image, creating a bump of radius to 800 and of scale 2.

filter := CIFilter filterWithName:'CIBumpDistortion'.
filter setValue:image forKey:'inputImage'.
filter setValue:(CIVector vectorWithX:1000 Y:700) forKey:'inputCenter'.
filter setValue:900 forKey:'inputRadius'.
filter setValue:1 forKey:'inputScale'.

Now that the filter is configured, it will apply itself to our image when asked to provides its output, creating a new image and giving it back to us:

bumpedImage := filter valueForKey:'outputImage'.

We can now draw this new image on screen:

bumpedImage drawInRect:(200<>80 extent:300<>200) 
fromRect:image extent operation:NSCompositeSourceOver fraction:1.


Figure 3. Our image after processing by a Core Image "bump" filter

To understand how the filter works, it is interesting to change its configuration (for instance, the values of its radius and its scale) and to regenerate and redisplay the image. If you are sitting behind an F-Script console, you are encouraged to do so!

Using blocks to create an animation

Now that we know how to process and display an image, we can create a nice little animation by repeatedly processing the image with a varying filter and displaying the result. To do that we just need to learn how write a loop using F-Script.

But, wait a minute... Isn't F-Script supposed to have a very simple syntax, where everything is expressed by sending messages to objects? Well, this is exact and, in fact, F-Script does not have any special syntax for control structures such as loops or conditionals. So the question here is "How can we express useful programs without such syntax?" To answer that, let me introduce you to the concept of code blocks in F-Script. Below, we see a code block in Objective-C and one in F-Script. Note the use of brackets in F-Script, instead of curly braces.

Objective-C F-Script (i.e., Smalltalk)
{
instruction1;
instruction2;
}
[
instruction1.
instruction2.
]

The code blocks look similar, but the way they work is quite different. In Objective-C, when the computer executes the code block, it simply executes the instructions in it immediately. In F-Script, the code block is actually a kind of literal notation for an object that contains the instructions. In other words, a block represents a deferred sequence of actions. In F-Script, the presence of a code block does not lead to the execution of its content, but to the creation of a block object, that can then be asked to execute the instructions. To do that, we send the "value" message to the block. The result returned by the execution of a block is the result of the evaluation of its last instruction.

As you can see below, F-Script blocks can have local variables, just like in Objective-C. If the instructions in the block refer to a variable that is not declared as local, F-Script will look for it in the enclosing lexical context of the block, as is the case in Objective-C.

Objective-C F-Script (i.e., Smalltalk)
{
id local1,local2;

instruction1;
instruction2;
}
[
|local1 local2|

instruction1.
instruction2.
]

The main point to understand here is that F-Script blocks are objects. Like with any object, you can send messages to a block, you can assign a block to a variable, store a block in a collection, pass a block as an argument to a method, archive a block on-disk, and so on. Blocks are not unique to F-Script (or Smalltalk). They are present in numerous languages (sometimes under the name of "closure" or "lambda expressions") such as Ruby, Python, Lisp, GroovyGroovy, and the forthcoming C# 3.

Now that we have blocks, it is easy to do conditional evaluation. Boolean objects provide a method named ifTrue: which takes a block as argument. If the value of the Boolean is true, then the block is executed by the method.

Objective-C F-Script (i.e., Smalltalk)
if (a > b) 
{
instructions
}
(a > b) ifTrue:
[
instructions
]

Boolean objects also have a method named ifTrue:ifFalse: that lets you have something equivalent to the if/else control structure of Objective-C. This method takes two blocks as arguments. One that gets executed if the booleanBoolean is true and the other one that gets executed if the booleanBoolean is false.

Objective-C F-Script
if (a > b) 
{
  instructions
}
else
{
  instructions
}
(a > b) ifTrue:
[
  instructions
]
ifFalse:
[
  instructions
]	

For performing our animation, we need a way to repeatedly evaluate a block. Let's review how F-Script provides this.

Blocks provide a method named whileTrue:, which takes another block as argument. The receiver of the whileTrue: message evaluates itself, and, if the result of this evaluation is a booleanBoolean with a value of true, the argument gets evaluated. This process is repeated as long as the receiver evaluates to true.+

Note that in the example with conditionals, the ifTrue: message was sent to a booleanBoolean object. In the latest example, the whileTrue: message is sent to a block that returns a booleanBoolean. This is very different. Indeed, it would not make sense to implement a whileTrue: method in the booleanBoolean class. This is because the value of a particular booleanBoolean never changes; whereas the value returned by the evaluation of a block can change from one evaluation to another.

Now that we know how to express repetitive evaluation, we can finally write our animation:

keyWindow := NSApplication sharedApplication keyWindow.
rect := (200<>100 extent:300<>200).
i := 0.
[i < 2500] whileTrue:
[
    filter setValue:(CIVector vectorWithX:i Y:700) forKey:'inputCenter'.
    bumpedImage := filter valueForKey:'outputImage'.
    bumpedImage drawInRect:rect fromRect:image extent ¬ 
    operation:NSCompositeSourceOver fraction:1.
    keyWindow flushWindow.
    i := i + 5.
]

As you can see, we move the bump across the image, by varying the X component of the CIVector object that define the center of the bump. We use a control variable named "i" that we increment by five at each iteration of our loop until it becomes equal to 2500. We also ask the window to flush itself at each step of our iteration in order to display the new image and produce the animation effect.

Blocks with arguments

For such kind of iteration, however, a for loop is more appropriate, and you might wonder if F-Script provides it. Well, it does! But in order to master it we must learn another feature of blocks: support for arguments. Block arguments are declared at the beginning of the block, just after the opening bracket. Each argument name is specified after a colon and a vertical bar ends the argument list. A block must then be executed using an appropriate "value..." message. For example, here is a block with no argument. We evaluate it by sending it the value message.

['hello world'] value      returns       'hello world'

Below is a block with one argument. In this case, we send a value: message, specifying the argument that will be passed to the block.

[:a| a class] value:'a string'      returns       String

Here is a block with two arguments. To evaluate it, we send it a value:value: message.

[:a :b| a + b] value:2 value:3      returns       5

Now that we have blocks with arguments, we can make use of powerful methods. For example, numbers have a method named to:do: which takes an number and a block as arguments. The block is evaluated for each integer between the receiver and the first argument (both included).

Objective-C F-Script
for (int i=0; i <= 100; i++) 
{
  instructions using i
}
 0 to:100 do:
[:i|
  instructions using i
]	

F-Script also provides a to:by:do: method that let us specify an iteration step.

Objective-C F-Script
for (int i=0; i <= 100; i = i + 5) 
{
  instructions using i
}
0 to:100 by:5 do:
[:i|
  instructions using i
] 

We can make use of it in our animation script, which then becomes:

keyWindow := NSApplication sharedApplication keyWindow.
rect := (200<>100 extent:300<>200).
0 to:2500 by:5 do:
[:i|
    filter setValue:(CIVector vectorWithX:i Y:700) forKey:'inputCenter'.
    bumpedImage := filter valueForKey:'outputImage'.
    bumpedImage drawInRect:rect fromRect:image extent 
operation:NSCompositeSourceOver fraction:1.
    keyWindow flushWindow.
]

You can change the value of the step to see how it makes the animation faster or slower.

Conclusion

Now that you are familiar with F-Script, you can use it whenever you want to explore a new Objective-C API, interactively prototype code or debug an application. And since you can easily embed it into your own application, you can provide your users with an interactive and scripting layer for your application's functionalities, by just exposing them as Objective-C objects.


Philippe Mougin is the creator of F-Script. He works at OCTO Technology, a French consulting company, where he explores and promotes the use of dynamic languages in enterprise systems. You can reach him at pmougin@acm.org.

 

Community Search:
MacTech Search:

Software Updates via MacUpdate

Latest Forum Discussions

See All

Pack a magnifying glass and practice you...
Somehow it has already been a year since Torchlight: Infinite launched, and XD Games is celebrating by blending in what sounds like a truly fantastic new update. Fans of Cthulhu rejoice, as Whispering Mist brings some horror elements, and tests... | Read more »
Summon your guild and prepare for war in...
Netmarble is making some pretty big moves with their latest update for Seven Knights Idle Adventure, with a bunch of interesting additions. Two new heroes enter the battle, there are events and bosses abound, and perhaps most interesting, a huge... | Read more »
Make the passage of time your plaything...
While some of us are still waiting for a chance to get our hands on Ash Prime - yes, don’t remind me I could currently buy him this month I’m barely hanging on - Digital Extremes has announced its next anticipated Prime Form for Warframe. Starting... | Read more »
If you can find it and fit through the d...
The holy trinity of amazing company names have come together, to release their equally amazing and adorable mobile game, Hamster Inn. Published by HyperBeard Games, and co-developed by Mum Not Proud and Little Sasquatch Studios, it's time to... | Read more »
Amikin Survival opens for pre-orders on...
Join me on the wonderful trip down the inspiration rabbit hole; much as Palworld seemingly “borrowed” many aspects from the hit Pokemon franchise, it is time for the heavily armed animal survival to also spawn some illegitimate children as Helio... | Read more »
PUBG Mobile teams up with global phenome...
Since launching in 2019, SpyxFamily has exploded to damn near catastrophic popularity, so it was only a matter of time before a mobile game snapped up a collaboration. Enter PUBG Mobile. Until May 12th, players will be able to collect a host of... | Read more »
Embark into the frozen tundra of certain...
Chucklefish, developers of hit action-adventure sandbox game Starbound and owner of one of the cutest logos in gaming, has released their roguelike deck-builder Wildfrost. Created alongside developers Gaziter and Deadpan Games, Wildfrost will... | Read more »
MoreFun Studios has announced Season 4,...
Tension has escalated in the ever-volatile world of Arena Breakout, as your old pal Randall Fisher and bosses Fred and Perrero continue to lob insults and explosives at each other, bringing us to a new phase of warfare. Season 4, Into The Fog of... | Read more »
Top Mobile Game Discounts
Every day, we pick out a curated list of the best mobile discounts on the App Store and post them here. This list won't be comprehensive, but it every game on it is recommended. Feel free to check out the coverage we did on them in the links below... | Read more »
Marvel Future Fight celebrates nine year...
Announced alongside an advertising image I can only assume was aimed squarely at myself with the prominent Deadpool and Odin featured on it, Netmarble has revealed their celebrations for the 9th anniversary of Marvel Future Fight. The Countdown... | Read more »

Price Scanner via MacPrices.net

Every model of Apple’s 13-inch M3 MacBook Air...
Best Buy has Apple 13″ MacBook Airs with M3 CPUs in stock and on sale today for $100 off MSRP. Prices start at $999. Their prices are the lowest currently available for new 13″ M3 MacBook Airs among... Read more
Sunday Sale: Apple iPad Magic Keyboards for 1...
Walmart has Apple Magic Keyboards for 12.9″ iPad Pros, in Black, on sale for $150 off MSRP on their online store. Sale price for online orders only, in-store price may vary. Order online and choose... Read more
Apple Watch Ultra 2 now available at Apple fo...
Apple has, for the first time, begun offering Certified Refurbished Apple Watch Ultra 2 models in their online store for $679, or $120 off MSRP. Each Watch includes Apple’s standard one-year warranty... Read more
AT&T has the iPhone 14 on sale for only $...
AT&T has the 128GB Apple iPhone 14 available for only $5.99 per month for new and existing customers when you activate unlimited service and use AT&T’s 36 month installment plan. The fine... Read more
Amazon is offering a $100 discount on every M...
Amazon is offering a $100 instant discount on each configuration of Apple’s new 13″ M3 MacBook Air, in Midnight, this weekend. These are the lowest prices currently available for new 13″ M3 MacBook... Read more
You can save $300-$480 on a 14-inch M3 Pro/Ma...
Apple has 14″ M3 Pro and M3 Max MacBook Pros in stock today and available, Certified Refurbished, starting at $1699 and ranging up to $480 off MSRP. Each model features a new outer case, shipping is... Read more
24-inch M1 iMacs available at Apple starting...
Apple has clearance M1 iMacs available in their Certified Refurbished store starting at $1049 and ranging up to $300 off original MSRP. Each iMac is in like-new condition and comes with Apple’s... Read more
Walmart continues to offer $699 13-inch M1 Ma...
Walmart continues to offer new Apple 13″ M1 MacBook Airs (8GB RAM, 256GB SSD) online for $699, $300 off original MSRP, in Space Gray, Silver, and Gold colors. These are new MacBook for sale by... Read more
B&H has 13-inch M2 MacBook Airs with 16GB...
B&H Photo has 13″ MacBook Airs with M2 CPUs, 16GB of memory, and 256GB of storage in stock and on sale for $1099, $100 off Apple’s MSRP for this configuration. Free 1-2 day delivery is available... Read more
14-inch M3 MacBook Pro with 16GB of RAM avail...
Apple has the 14″ M3 MacBook Pro with 16GB of RAM and 1TB of storage, Certified Refurbished, available for $300 off MSRP. Each MacBook Pro features a new outer case, shipping is free, and an Apple 1-... Read more

Jobs Board

*Apple* Systems Administrator - JAMF - Activ...
…**Public Trust/Other Required:** None **Job Family:** Systems Administration **Skills:** Apple Platforms,Computer Servers,Jamf Pro **Experience:** 3 + years of Read more
IT Systems Engineer ( *Apple* Platforms) - S...
IT Systems Engineer ( Apple Platforms) at SpaceX Hawthorne, CA SpaceX was founded under the belief that a future where humanity is out exploring the stars is Read more
Nurse Anesthetist - *Apple* Hill Surgery Ce...
Nurse Anesthetist - Apple Hill Surgery Center Location: WellSpan Medical Group, York, PA Schedule: Full Time Sign-On Bonus Eligible Remote/Hybrid Regular Apply Now Read more
Housekeeper, *Apple* Valley Village - Cassi...
Apple Valley Village Health Care Center, a senior care campus, is hiring a Part-Time Housekeeper to join our team! We will train you for this position! In this role, Read more
Sublease Associate Optometrist- *Apple* Val...
Sublease Associate Optometrist- Apple Valley, CA- Target Optical Date: Apr 20, 2024 Brand: Target Optical Location: Apple Valley, CA, US, 92307 **Requisition Read more
All contents are Copyright 1984-2011 by Xplain Corporation. All rights reserved. Theme designed by Icreon.