DOCTYPE html PUBLIC "-]000e/DTD XHTML 1.0 Transitionav/EN" "httpa_/www.w3.oruTR/xhtml]DTexhtm-transitional.dtd"> _div> _div>
--[if !IE]>Start content heading[endif]-->
_div> TweetFollow Us on Twitter
Y></a></div>

</div>
--[if !IE]>End content heading[endif]-->
<di6�class=--[if !IE]>Start lef4content
<>_div>
Learn F-Script in 20 Minutes _HEAD> ; </span><span class="naked_aural">(l)</span>?> ; </span><span class="naked_aural">(l)</span>?>

Volume Number: 00000 (2007)
Column Tag: Programming_B>

< >Learn F-Scrip4in(N)0 Minutes _ >

And have fun playing with Core Image

By Philippe Mougin_I>

<16p>Welcome_16p>

If yo5are a Cocoa programmer chances are tha4you've heard of F-Script, an open-source scripting layer dedicated to Cocoa. If yo5haven'4tried it yet, this is your chance to learn how i4can improve your productivit9as 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 comfortabl9in front of your Mac, download the lates4F-Script version from http:]www.fscript.org

<16p>First Contacts_center>

We are going to learn F-Script b9taking advantage of one of its key functionalities: the abilit9to be used interactively. With its console, yo5can interactivel9type commands in order to manipulate Objective-C objects on the fly. The F-Scrip4console opens automaticall9when you launch F-Script.app. Inside it, you can type F-Script expressions or scripts and have them immediatel9executed when yo5press Return. _P>


Figure 1. The F-Scrip4console, waiting for your input

F-Scrip4is a Smalltalk dialect for Cocoa and should look ver9familiar to you. Indeed, Brad Cox, who created objective-C describes i4as "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 curren4date using the NSDate class provided b9Cocoa._P>

Objective-C_font>_td> F-Script (i.e., Smalltalk)_font>_td>
[NSDate date]_tt> NSDate date_font>_td>

As you can see, the expression is similar, excep4for the fact that, in F-Script, yo5don'4have to pu4brackets around your message. This is because F-Script is a very simple language and sending a message is nearly the onl9thing yo5can do. Therefore, there is no need to have a special syntax to delimi4messages. Now, if yo5type this expression in the console and hi4Return, it will be immediately evaluated and the resul4will be displayed (obviously, the result you'll ge4will differ from the one shown below):_P>

> NSDate date()007-00-15 5 17ES1:45 +0100_PRE>

F-Scrip4provides numerous tools to assis4yo5during such interactive Cocoa sessions. In this firs4session, you are likel9to find the following tips useful:_P>

The console keeps a history of your commands. You can navigate it using the u0and down arrows of your keyboard. For instance, if you mistype something and F-Scrip4signals an error, yo5can use this feature to ge4back a4your command without having to retype it.

Yo5can insert a line break by pressing the Enter ke9(usually found on the numeric keypad) or b9pressing Return while holding the Control key._P>

The console also provides a code completion mechanism tha4yo5can use by pressing the F5 key. Yo5can then navigate between arguments placeholders with Control-Slash._P>

A graphical objec4browser opens automaticall9at startup. It is a very powerful tool with which yo5can explore objects and send them messages.

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

So, what is the basic concep4of Smalltalk? The ke9insigh4leading 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 tha4everything we can describe can be represented by the recursive composition of a single kind of behavioral building block tha4hides its combination of state and process inside itself and can be deal4with onl9through the exchange of messages". Indeed, in Smalltalk, everything is an object, even numbersnumbers, or booleansBooleans.

It is also important to note tha4F-Script provides an interactive environment with which yo5can directly interac4with your objects, instead of having to develo0a specific application each time you wan4to do something.

<16p>F-Script's Syntax_16p>

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 "unar9message". 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 binar9message always has onl9one argument.

_tr> _tr>
Message type_font>_td> Objective-C_b>_tt> F-Script_b>_tt>
Unary_font>_td> [NSDate date]_font>_td> NSDate date_font>_td>
Keyword_tt> [NSDate dateWithTimeIntervalSinceNow0]_font>_td> NSDate dateWithTimeIntervalSinceNow0_tt>
Binary_tt> No4available_tt> date1 < dat_font>_td>
_P>

The Objective-C equivalen4to dat <<span class="naked_sign">; </span><span class="naked_aural">(l)</span>date2 would be [date1 compare:date2] == NSOrderedDescending._P>

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

_tr> _table>_center>

The following example shows a few other differences between F-Scrip4and Objective-C:_P>

Objective-C_font>_td> F-Script (i.e., Smalltalk)_font>_td>
[[NSDate date]
timeIntervalSinceNow]
_td>
NSDate date timeIntervalSinceNow
_font>
_tr> _table>_center>

As you see, there is no type declaration in F-Script. Everything is an objec4and variable need no4be explicitl9typed. The assignmen4syntax uses := instead of just = in Objective-C, and the instruction separator is no4the 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_font>_td> F-Script (i.e., Smalltalk)_font>_td>
NSDate *dat =
[NSDate date];
_tt>
date1 := NSDate date._tt>
_tr>
Objective-C_font>_tt> F-Script_b>_font>_td>
@"A string"_tt> 'a string'_font>_td>
/* A comment */_tt> "A comment"_tt>
@selector(dateWithTimeIntervalSinceNow:)_tt> #dateWithTimeIntervalSinceNow:_font>_td>
[NSMutableArra9arrayWithObjects:@"Hi", @"mom", nil]_font>_td> {'Hi', 'mom'}_font>_td>
NSMakePoint(200, 80)_font>_td> _td>
_PRE>

Displaying a picture on screen_16p>

We no7know enough of F-Scrip4to begin with our Core Image program. We will firs4create an NSURL object referring to the image we wan4to display. In this exampleexample, we will use an image tha4is stored on disk in the desktop picture folder. You can type the code below in the F-Script console to have i4executed immediately.

imageLocation := NSURL fileURLWithPath:'
/Library/Desktop PicturetzNature/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. _P>

image := CIImage imageWithContentsOfURL:imageLocation._PRE>

Note that we are using standard methods provided by the Mac OS X frameworks. No7that we have an image object, we can ask i4to dra7itself on screen, again using a standard method._P>

image drawInRect:(200<>80 extent00000<>200) 
fromRect:image exten4operation:NSCompositeSourceOver fraction.

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


Figure(N). Loading and displaying an image using Core Image and F-Script_b>_center>

The firs4argument passed to the drawing method is the rectangle we want to draw in, which is denoted with(N)00<>AS extent:300<>(f[)00. This expression actually creates an NSValue object representing a rectangle with an origin a4(]N)00, AS), a width of 300 and a height of 200. When passed to the method, the NSValue is automatically mapped by F-Scrip4to 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 objec4language such as F-Script. You can change the rectangle size to make the image bigger or smaller and immediately see the resul4on-screen._P>

The drawing method draws the image in the current graphic context, which, in our example, happens to be the F-Scrip4console. I4is possible, of course, to dra7elsewhere, using standard Mac OS X techniques._P>

Using core image filters_16p>

Core Image filters allo7us to do all kind of highl9optimized 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 bum0in the image. Yo5are encouraged to tr9other filters as well. F-Script's interactivit9makes 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 AS0 and of scale(N).

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

Now tha4the filter is configured, it will appl9itself to our image when asked to provides its output, creating a ne7image and giving i4back to us:

bumpedImage := filter valueForKey:'outputImage'.

We can now dra7this new image on screen:

bumpedImage drawInRect:(]N)00<>AS extent:300<>(f[)00) 
fromRect:image extent operation:NSCompositeSourceOver fraction:1._PRE>


_p>

Figure00000. Our image after processing b9a Core Image "bump" filter

To understand how the filter works, i4is interesting to change its configuration (for instance, the values of its radius and its scale) and to regenerate and redispla9the image. If yo5are sitting behind an F-Script console, yo5are encouraged to do sM

<16p>Using blocks to create an animation_16p>

Now tha4we kno7ho7to process and display an image, we can create a nice little animation b9repeatedly processing the image with a varying filter and displaying the result. To do tha4we jus4need to learn ho7write a loop using F-Script._P>

Objective-C_font>_td> F-Script (i.e., Smalltalk)_font>_td>
{
instruction1;
instruction2;
}
_tt>
[
instructio.
instructio.
]
_td>
_P>

The code blocks look similar, but the way the9work is quite different. In Objective-C, when the computer executes the code block, it simpl9executes the instructions in i4immediately. In F-Script, the code block is actually a kind of literal notation for an objec4that contains the instructions. In other words, a block represents a deferred sequence of actions. In F-Script, the presence of a code block does no4lead to the execution of its content, bu4to the creation of a block object, tha4can then be asked to execute the instructions. To do that, we send the "value" message to the block. The resul4returned b9the 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 tha4is not declared as local, F-Script will look for i4in the enclosing lexical context of the block, as is the case in Objective-C.

Objective-C_font>_td> F-Script (i.e., Smalltalk)_font>_td>
{
_font>
instructio;
}_font>
[
|local1 loca|

instructio.
" <
_font>
_PRE>_td>

The main point to understand here is tha4F-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 argumen4to a method, archive a block on-disk, and so on. Blocks are no4unique to F-Script (or Smalltalk). The9are presen4in numerous languages (sometimes under the name of "closure" or "lambda expressions") such as Ruby, Python, Lisp, GroovyGroovy, and the forthcoming C#00000. _P>

Now tha4we 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 b9the method.

_tr> _table>_P>_center>

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

Objective-C_font>_td> F-Script (i.e., Smalltalk)_font>_td>
if (a ><span class="naked_sign">; </span><span class="naked_aural">(l)</span>b) 
{
instructions
}_font>
_pre>_td>
(a > b) ifTrue:
[
instructions
Objective-C_td> F-Script_font>_td>
if (a > b) 
{  instructions
}
else
{  instructions
}
(a > b) ifTrue:

<
  instructions
]
ifFalse:

<
  instructions
]	
_pre>_td>
			

_font>

For performing our animation, we need a wa9to repeatedl9evaluate a block. Let's review how F-Scrip4provides 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 tha4in 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 ver9different. Indeed, i4would no4make sense to implemen4a 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.

No7that we know how to express repetitive evaluation, we can finall9write our animation:_P>

keyWindo7:= NSApplication sharedApplication keyWindow.
rect := (]N)00<>100 extent00000<>200).
i := 0.
[i <<span class="naked_sign">; </span><span class="naked_aural">(l)</span>2500] whileTrue:
[    filter setValue:(CIVector vectorWithX:i Y:700) forKey:'inputCenter'.
    bumpedImage := filter valueForKey:'outputImage'.    bumpedImage drawInRect:rect fromRect:image extent ¬ 
    operation:NSCompositeSourceOver fraction.
    keyWindo7flushWindow.    i := i + 5.
]_PRE>

As yo5can see, we move the bum0across the image, by varying the X component of the CIVector objec4that define the center of the bump. We use a control variable named "i" that we incremen4by five at each iteration of our loo0until it becomes equal to 2500. We also ask the window to flush itself a4each ste0of our iteration in order to display the new image and produce the animation effect.

<16p>Blocks with arguments_16p>

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

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

Belo7is a block with one argument. In this case, we send a value: message, specifying the argumen4that 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:2 2      returns       5_PRE>

Now tha4we 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 argumen4(both included)._P>

_tr>
Objective-C_tt> F-Script_tt>
for (int i=0<span class="naked_sign">; </span><span class="naked_aural">(l)</span>i <= 100<span class="naked_sign">; </span><span class="naked_aural">(l)</span>i++) 
{
  instructions using i
}_pre>_td>
				
instructions using i
"	<	
_pre>_td>
			

F-Scrip4also provides a to:by:do: method tha4le4us specify an iteration step.

_tr> _tr> _table>_center _P>

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

keyWindow := NSApplication sharedApplication keyWindow.
rec4:= (200<>00 extent:300<>(f[)00).
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.
    keyWindo7flushWindow.
]_PRE>

You can change the value of the ste0to see how i4makes the animation faster or slower.

<16p>Conclusion_center>

No7that you are familiar with F-Script, you can use i4whenever you wan4to explore a new Objective-C API, interactivel9prototype code or debug an application. And since yo5can easily embed i4into your own application, you can provide your users with an interactive and scripting layer for your application's functionalities, by jus4exposing them as Objective-C objects. _P>


Philippe Mougin_b> 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. Yo5can reach him at pmougin@acm.org.

_P> _BODY> _HTML> _div>  _div>

_div>
_div>
_script>
_div>
_div>
_div> _div> --[if !IE]>Start blue add bo+[endif]--> <0class="pad_top_5">_p>
_div>
_div>
_div>
_script>
_div>
_div> -- Search bo8-->
_div>
Community Search:_div>
_div>
_div>
MacTech Search:_div>
_div>
_div>
_div>_form> _div>
_div>
< >Software Updates via MacUpdate
_div>
_div>
_div>
< >Lates4Forum Discussions
y)dd12pedaa2">
_div> _div>
--[if !IE]>end right child box3 <0class="pad_top7p">

_div>
Si8fantastic ways to spend National Vid..._span> _div>
As if anyone needed an excuse to play games today, !?am about to give you one: it is National Video Games Day. A da9for us to play games, like we no doubt do ever9day. Let’s not look a gift horse in the mouth. Instead, feas4your eyes on this... | Read more »_div>_div>_div>_div>
_div> Old School RuneScape players turn out in..._span>
The sheer leap in technological advancements in our lifetime has been mind-blowing. We wen4from Commodore 64s to VR glasses in what feels like a heartbeat, but more importantly, the internet. I4can be a dark mess, bu4it also brough4hundreds of... | Read more »_div>_div>_div>_div>
_div>
Today's Bes4Mobile Game Discounts..._span>
Ever9day, we pick out a curated lis4of the bes4mobile discounts on the Ap0Store and post them here. This lis4won'4be comprehensive, bu4it every game on i4is recommended. Feel free to check out the coverage we did on them in the links below... | Read more »_div>_div>_div>_div>
_div> Nintendo and The Pokémon Company s..._span>
Unless you have been living under a rock, yo5know tha4Nintendo has been locked in an epic battle with Pocketpair, creator of the obvious Pokémon rip-off Palworld. Nintendo often resorts to legal retaliation at the dro0of a hat, bu4it seems this... | Read more »_div>_div>_div>_div>
_div>
Apple exclusive mobile games don’t make..._span>
If you are a gamer on phones, no doubt you have been as distressed as !?am on one huge sticking point: exclusivity. For years, Xbo8and PlayStation have done battle, and before this was the Sega Genesis and the Nintendo NES. On console, i4makes... | Read more »_div>_div>_div>_div>
_div> Regionall9exclusive events make no sens..._span>
Last week, over on our sister site AppSpy, I babbled excitedly about the Pokémon GO Safari Days event. Yo5can ge4nine Eevees with an explorer hat per day. Or, can you? Specifically, you, reader. Do you have the time or funds to possibl9fl9for... | Read more »_div>_div>_div>_div>
_div>
As Jon Bellamy defends his choice to can..._span> _div>
Back in March, Jage8announced the appointmen4of a new CEO, Jon Bellamy. Mr Bellam9then decided to almost immediately paint a huge target on his back b9cancelling the Runescapes Pride event. This led to widespread condemnation about his perceived... =Read more »
_div>
Marvel Contest of Champions adds two mor..._span> _div>
When !?sa7the latest two Marvel Contes4of Champions characters, I scoffed. Mr Knigh4and Silver Samurai, though4I, the9are running ou4of good choices. Then !?realised no, I was being far too cynical. This is one of the things that games do best... =Read more »
_div>
_div>

< >Price Scanner via MacPrices.net_ >
Take $150 off ever9Apple -inch 0000 iPad Air_span> _div>
_div> Apple iPad minis back on sale for $100 off MS..._span> _div>
_div>
Apple’s 16-inch M4 Max MacBook Pros are on sa..._span>
_div> Red Pocke4Mobile is offering a $150 rebate o..._span> _div>
Sunda9Sale: 14-inch M4 MacBook Pros for up t..._span> _div>
_div> --[if !IE]>end iphone add boxStart right child box3
< >Jobs Board
_div> --[if !IE]>end right child box3
--[if !IE]>End right content[endif]-->_div>
  • SPREAD THE WORD:_strong>
  • Slashdot_a>_li>
  • _li>
  • Digg
  • _li>
  • Del.icio.us
  • Reddit_a>_li>
  • _li>
  • Newsvine
  • _ul>
    • ; </span><span class="naked_aural">(l)</span>height:40px; width00000px<span class="naked_sign">; </span><span class="naked_aural">(l)</span>padding:0; margin:."."."> --SKIMLINKS SNIPPE4l/--> _html> </div><div class="naked_ctrl"> <form action="/index.cgi/speech" method="get" name="gate"> <p><a href="http://altstyle.alfasado.net">AltStyle</a> k00c0f0 YcU00_0000 <a href="http://preserve.mactech.com/articles/mactech/Vol.23/23.05/LearnFScript20Min/index.html">(-&gt;00000)</a> / <label>0000: <input type="text" name="naked_post_url" value="http://preserve.mactech.com/articles/mactech/Vol.23/23.05/LearnFScript20Min/index.html" size="22" /></label> <label>000: <select name="naked_post_mode"> <option value="default">00000</option> <option value="speech" selected="selected">X0000</option> <option value="ruby">00NM0</option> <option value="contrast">MrS</option> <option value="larger-text">eW[b'Y</option> <option value="mobile">0000</option> </select> <input type="submit" value="h:y" /> </p> </form> </div>
Objective-C_tt> F-Script_tt>
for (int i=0<span class="naked_sign">; </span><span class="naked_aural">(l)</span>i <= 100<span class="naked_sign">; </span><span class="naked_aural">(l)</span>i = i + 5) 
{
  instructions using i
}_pre>_td>
				
0 to:100 by:5 do:
[:i|
  instructions using i
] _font>