root/docs/nowelium/ioDocs/IoGuide_ja.html @ 8424

Revision 8424, 57.8 kB (checked in by nowelium, 7 years ago)
Line 
1<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN">
2<html>
3<head>
4<meta http-equiv="Content-Type" content="text/html;charset=utf-8">
5<title>Io プログラミングガイド</title>
6<META HTTP-EQUIV="EXPIRES" CONTENT=0>
7<link rel="stylesheet" href="docs.css">
8</head>
9<body>
10
11<h1>Io プログラミングガイド</h1>
12<p>
13<br>
14
15<table style="width:47em">
16<tr>
17<td valign=top style="width:33%">
18
19<div class=indexSection><a href="#Introduction">はじめに</a></div>
20<div class=indexItem><a href="#Introduction-Perspective">観点</a></div>
21<div class=indexItem><a href="#Introduction-Getting-Started">はじめましょう</a></div>
22<div class=indexItem><a href="#Introduction-Downloading">ダウンロード</a></div>
23<div class=indexItem><a href="#Introduction-Installing">インストール</a></div>
24<div class=indexItem><a href="#Introduction-Binaries">バイナリ</a></div>
25<div class=indexItem><a href="#Introduction-Running-Scripts">スクリプトの実行</a></div>
26<div class=indexItem><a href="#Introduction-Interactive-Mode">対話モード</a></div>
27
28<div class=indexSection><a href="#Syntax">構文</a></div>
29<div class=indexItem><a href="#Syntax-Expressions">式</a></div>
30<div class=indexItem><a href="#Syntax-Messages">メッセージ</a></div>
31<div class=indexItem><a href="#Syntax-Operators">演算子</a></div>
32<div class=indexItem><a href="#Syntax-Assignment">代入</a></div>
33<div class=indexItem><a href="#Syntax-Numbers">数値</a></div>
34<div class=indexItem><a href="#Syntax-Strings">文字列</a></div>
35<div class=indexItem><a href="#Syntax-Comments">コメント</a></div>
36
37
38<div class=indexSection><a href="#Objects">オブジェクト</a></div>
39<div class=indexItem><a href="#Objects-Overview">概略</a></div>
40<div class=indexItem><a href="#Objects-Prototypes">プロトタイプ</a></div>
41<div class=indexItem><a href="#Objects-Inheritance">継承</a></div>
42<div class=indexItem><a href="#Objects-Methods">メソッド</a></div>
43<div class=indexItem><a href="#Objects-Blocks">ブロック</a></div>
44<div class=indexItem><a href="#Objects-Forward">転送</a></div>
45<div class=indexItem><a href="#Objects-Resend">Resend</a></div>
46<div class=indexItem><a href="#Objects-Super">Super</a></div>
47<div class=indexItem><a href="#Objects-Introspection">イントロスペクション</a></div>
48
49
50</td>
51<td valign=top style="width:33%">
52
53<div class=indexSection><a href="#Control-Flow">制御構造</a></div>
54<div class=indexItem><a href="#Control-Flow-true-false-and-nil">true, false と nil</a></div>
55<div class=indexItem><a href="#Control-Flow-Comparison">比較</a></div>
56<div class=indexItem><a href="#Control-Flow-Conditions">条件分岐</a></div>
57<div class=indexItem><a href="#Control-Flow-Loops">ループ</a></div>
58
59
60<div class=indexSection><a href="#Importing">Importing</a></div>
61
62<div class=indexSection><a href="#Concurrency">並行動作</a></div>
63<div class=indexItem><a href="#Concurrency-Coroutines">コルーチン</a></div>
64<div class=indexItem><a href="#Concurrency-Scheduler">スケジューラ</a></div>
65<div class=indexItem><a href="#Concurrency-Actors">アクタ</a></div>
66<div class=indexItem><a href="#Concurrency-Futures">Future</a></div>
67<div class=indexItem><a href="#Concurrency-Yield">Yield</a></div>
68<div class=indexItem><a href="#Concurrency-Pause and Resume">Pause and Resume</a></div>
69
70<div class=indexSection><a href="#Exceptions">例外</a></div>
71<div class=indexItem><a href="#Exceptions-Raise">Raise</a></div>
72<div class=indexItem><a href="#ExceptionsTry-and-Catch">Try and Catch</a></div>
73<div class=indexItem><a href="#Exceptions-Pass">Pass</a></div>
74<div class=indexItem><a href="#Exceptions-Custom-Exceptions">カスタム例外</a></div>
75
76<div class=indexSection><a href="#Unicode">Unicode</a></div>
77<div class=indexItem><a href="#Unicode-Sequences">Sequences</a></div>
78<div class=indexItem><a href="#Unicode-Source">Source</a></div>
79<div class=indexItem><a href="#Unicode-Conversion">変換</a></div>
80
81</td>
82<td valign=top style="width:33%">
83
84<!--
85<div class=indexSection>Metaprogramming</div>
86<div class=indexItem><a href=>Object</a></div>
87<div class=indexItem><a href=>Block</a></div>
88<div class=indexItem><a href=>Message</a></div>
89<div class=indexItem><a href=>Syntax</a></div>
90-->
91
92<div class=indexSection><a href="#Primitives">プリミティブ</a></div>
93<div class=indexItem><a href="#Primitives-Object">オブジェクト</a></div>
94<div class=indexItem><a href="#Primitives-List">リスト</a></div>
95<div class=indexItem><a href="#Primitives-Sequence">Sequence</a></div>
96<div class=indexItem><a href="#Primitives-Ranges">Ranges</a></div>
97<div class=indexItem><a href="#Primitives-File">ファイル</a></div>
98<div class=indexItem><a href="#Primitives-Directory">ディレクトリ</a></div>
99<div class=indexItem><a href="#Primitives-Date">日付</a></div>
100<div class=indexItem><a href="#Primitives-Networking">ネットワーク</a></div>
101<div class=indexItem><a href="#Primitives-XML">XML</a></div>
102<div class=indexItem><a href="#Primitives-Vector">Vector</a></div>
103
104<div class=indexSection><a href="#Embedding">組み込み</a></div>
105<div class=indexItem><a href="#Embedding-Conventions">Conventions</a></div>
106<div class=indexItem><a href="#Embedding-IoState">IoState</a></div>
107<div class=indexItem><a href="#Embedding-Values">Values</a></div>
108
109<div class=indexSection><a href="#Bindings">バインディング</a></div>
110
111<div class=indexSection><a href="#Appendix">付録</a></div>
112<div class=indexItem><a href="#Appendix-Grammar">文法</a></div>
113<div class=indexItem><a href="#Appendix-Credits">協力者</a></div>
114<div class=indexItem><a href="#Appendix-References">参考</a></div>
115<div class=indexItem><a href="#Appendix-License">ライセンス</a></div>
116
117</td>
118</tr>
119</table>
120
121<p>
122
123<h2>はじめに<a name="Introduction"></a></h2>
124<div class=indent>
125
126<div class=quote>
127Simplicity is the essence of happiness.<br>
128- Cedric Bledsoe
129</div>
130
131Io はプロトタイプベースの動的言語である。 The ideas in Io are mostly inspired by Smalltalk[1] (all values are objects), Self[2] (prototype-based), NewtonScript[3] (differential inheritance), Act1[4] (actors and futures for concurrency), Lisp[5] (code is a runtime inspectable / modifiable tree) and Lua[6] (small, embeddable).
132
133<a name="Introduction-Perspective"></a>
134<h3>観点</h3>
135
136
137<h4>Why Another Language?</h4>
138
139The focus of programming language research for the last thirty years has been to combine the expressive power of high level languages like Smalltalk and the performance of low level language like C with little attention paid to advancing expressive power itself. The result has been a series of languages which are neither as fast as C or as expressive as Smalltalk. Io's purpose is to refocus attention on expressiveness by exploring higher level dynamic programming features with greater levels of runtime flexibility and simplified programming syntax and semantics.
140
141<p>
142
143In Io, all values are objects (of which, anything can change at runtime, including slots, methods and inheritance), all code is made up of expressions (which are runtime inspectable and modifiable) and all expressions are made up of dynamic message sends (including assignment and control structures). Execution contexts themselves are objects and activatable objects such as methods/blocks and functions are unified into blocks with assignable scope. Concurrency is made more easily manageable through actors and implemented using coroutines for scalability.
144
145<h4>Goals</h4>
146
147To be a language that is:
148<p>
149
150simple
151<ul>
152<li>conceptually simple and consistent
153<li>easily embedded and extended
154</ul>
155powerful
156<ul>
157<li>highly dynamic and introspective
158<li>highly concurrent (via coroutines and async i/o)
159</ul>
160practical
161<ul>
162<li>fast enough
163<li>multi-platform
164<li>unrestrictive BSD/MIT license
165<li>comprehensive standard packages in distro
166</ul>
167
168</div>
169
170<h2>はじめましょう<a name="Introduction-Getting-Started"></a></h2>
171<div class=indent> 
172
173<a name="Introduction-Downloading"></a>
174<h3>ダウンロード</h3>
175
176Io の配布は以下から取得できます:
177<pre>
178<a href="http://iolanguage.com">http://iolanguage.com</a>
179</pre>
180
181<a name="Introduction-Installing"></a>
182<h3>インストール</h3>
183
184<h4>VM</h4>
185
186最初に Io vm をコンパイルします:
187
188<pre>
189make vm
190sudo make install
191</pre>
192
193
194<h4>アドオンが依存するライブラリのインストール</h4>
195
196いくつかの Io のアドオンは既にあなたのシステム上にインストールされているライブラリを必用とするかもしれません。 それらを自動的にインストールするのは次をタイプしてください:
197
198<pre>
199su -c "sudo make aptget"
200</pre>
201
202または:
203
204<pre>
205su -c "make emerge"
206</pre>
207
208または:
209
210<pre>
211sudo make port
212</pre>
213
214あなたの使用しているパッケージインストーラによって使い分けでください。
215(<a href="http://macports.org">port</a> is for OSX)
216
217<h4>アドオンのコンパイル</h4>
218
219ビルドをするには、トップディレクトリで以下を実行:
220
221<pre>
222make
223</pre>
224
225バイナリはサブフォルダ _build/binaries に置かれるでしょう。 インストールするには:
226
227<pre>
228sudo make install
229</pre>
230
231もしくは、インストールを、単にあなたの開発用フォルダにリンクするようにするには:
232
233<pre>
234sudo make linkInstall
235</pre>
236
237そしてすべてのユニットテストを実行するには:
238
239<pre>
240make test
241</pre>
242
243Don't worry if some of the addons won't build unless it's a particular addon that you need. Addons are just optional libraries.
244
245<h4>ノート</h4>
246
247特定のアドオンのみ make するには、以下のようにしてください:
248
249<pre>
250make AddonName
251</pre>
252
253ソースコントロール上のリポジトリから取得してきた後は、必ずしてください:
254
255<pre>
256make clean; make
257</pre>
258
259VM のテストのみ実行:
260
261<pre>
262make testvm
263</pre>
264
265
266<h4>バイナリ</h4>
267
268Io builds two executables and places them in the binaries folder. They are:
269
270<pre>
271io_static
272io
273</pre>
274
275The io_static executable contains the vm with a minimal set of primitives all statically linked into the executable. The io executable contains just enough to load the iovm dynamically linked library and is able to dynamically load io addons when they are referenced.
276
277
278<a name="Introduction-Running-Scripts"></a>
279<h3>スクリプトの実行</h3>
280
281スクリプトを実行する例:
282
283<pre>
284io samples/HelloWorld.io
285</pre>
286
287Io が最初に実行するものに、どんな main() 関数やオブジェクトも必要ありません。 スクリプトはコンパイルされると実行されます。
288
289<a name="Introduction-Interactive-Mode"></a>
290<h3>対話モード</h3>
291
292実行:
293
294<pre>
295./_build/binaries/io
296</pre>
297
298もし Io がインストール済みなら、以下のように実行:
299
300<pre>
301io
302</pre>
303
304Io のインタプリタプロンプトが引かれるでしょう。
305<p>
306直接入力する事で、コードを評価することができます。 例:
307
308<pre>
309Io> "Hello world!" println
310==> Hello world!
311</pre>
312
313式は Lobby のコンテキストにて評価される :
314
315<pre>
316Io> print
317[printout of lobby contents]
318</pre>
319
320あなたのホームフォルダに .iorc が存在する場合、対話モードのプロンプトが開始される前にそれが評価されます。
321
322
323<h4>オブジェクトのインスペクト</h4>
324
325このようにしてオブジェクトのスロットのリストを取得することができます:
326
327<pre>
328Io> someObject slotNames
329</pre>
330
331それらをソート順にするには:
332
333<pre>
334Io> someObject slotNames sort
335</pre>
336
337オブジェクトの記述がうまくフォーマットされた形式においては slotSummary メソッドが便利です:
338
339<pre>
340Io> slotSummary
341==>  Object_0x20c4e0:
342  Lobby            = Object_0x20c4e0
343  Protos           = Object_0x20bff0
344  exit             = method(...)
345  forward          = method(...)
346</pre>
347
348Exploring further:
349
350<pre>
351Io> Protos
352==>  Object_0x20bff0:
353  Addons           = Object_0x20c6f0
354  Core             = Object_0x20c4b0
355
356Io> Protos Addons
357==>  Object_0x20c6f0:
358  ReadLine         = Object_0x366a10
359</pre>
360
361Only ReadLine is seen in the Addons since no other Addons have been loaded yet.
362<p>
363Inspecting a method will print a decompiled version of it:
364
365<pre>
366Io> Lobby getSlot("forward")
367==> # io/Z_Importer.io:65
368method(
369    Importer import(call)
370)
371</pre>
372
373<h4>doFile と doString</h4>
374
375対話モードにて doFile メソッドを使用すると、スクリプトを実行することができる:
376
377<pre>
378doFile("scriptName.io")
379</pre>
380
381doFile はレシーバのコンテキストにて評価します。(この場合レシーバは lobby でしょう)。 他のオブジェクトのコンテキストにてスクリプトを評価するには、 doFile メッセージをそれに送信します:
382
383<pre>
384someObject doFile("scriptName.io")
385</pre>
386
387文字列を評価するには doString メソッドを使用することができます:
388
389<pre>
390Io> doString("1+1")
391==> 2
392</pre>
393
394また、特定のオブジェクトのコンテキストで文字列を評価するには:
395
396<pre>
397someObject doString("1 + 1")
398</pre>
399
400<h4>コマンドライン引数</h4>
401
402コマンドライン引数を出力する例:
403
404<pre>
405args foreach(k, v, write("'", v, "'\n"))
406</pre>
407
408<h4>launchPath</h4>
409
410System の "launchPath" スロットには、実行された最初のソースファイルの位置が格納されている。
411
412</div>
413<h2>構文<a name="Syntax"></a></h2>
414<div class=indent>
415
416<div class=quote>
417Less is more.<br>
418- Ludwig Mies van der Rohe
419</div>
420
421<a name="Syntax-Expressions"></a>
422<h3>式</h3>
423
424Io キーワードや文を持たない。 Everything is an expression composed entirely of messages, each of which is a runtime accessible object. 非公式の BNF 記述:
425
426<pre>
427exp        ::= { message | terminator }
428message    ::= symbol [arguments]
429arguments  ::= "(" [exp [ { "," exp } ]] ")"
430symbol     ::= identifier | number | string
431terminator ::= "\n" | ";"
432</pre>
433
434For performance reasons, String and Number literal messages have their results cached in their message objects.
435
436<a name="Syntax-Messages"></a>
437<h3>メッセージ</h3>
438
439メッセージ引数はレシーバに式として渡され評価される。 Selective evaluation of arguments can be used to implement control flow. 例:
440
441<pre>
442for(i, 1, 10, i println)
443a := if(b == 0, c + 1, d)
444</pre>
445
446上記コードでの、"for" と "if" は通常のメッセージであり、特殊形式やキーワードでは無い。
447<p>
448
449Likewise, dynamic evaluation can be used with enumeration without the need to wrap the expression in a block. 例:
450
451<pre>
452people select(person, person age < 30)
453names := people map(person, person name)
454</pre>
455
456Methods like map and select will typically apply the expression directly to the values if only the expression is provided:
457
458<pre>
459people select(age < 30)
460names := people map(name)
461</pre>
462
463There is also some syntax sugar for operators (including assignment), which are handled by an Io macro executed on the expression after it is compiled into a message tree. Some sample source code:
464
465<pre>
466Account := Object clone
467Account balance := 0
468Account deposit := method(amount,
469    balance = balance + amount
470)
471
472account := Account clone
473account deposit(10.00)
474account balance println
475</pre>
476
477Like Self[2], Io's syntax does not distinguish between accessing a slot containing a method from one containing a variable.
478
479<a name="Syntax-Operators"></a>
480<h3>演算子</h3>
481
482演算子とは、単に英数字以外の文字による名前をもつメソッドである。例外として、":"(コロン), "_"(アンダースコア), '"'(ダブルクォート), "."(ドット) は演算子に使えず、また次のものは英数字による名前だが演算子とする: "and", "or", "return". 例:
483
484<pre>
4851 + 2
486</pre>
487
488丁度次のような通常の形式のメッセージにコンパイルされる:
489
490<pre>
4911 +(2)
492</pre>
493
494括弧を使ってまとめることもできる:
495
496<pre>
4971 +(2 * 4)
498</pre>
499
500標準の演算子は、C 言語と同じ優先順位で処理される。従って:
501
502<pre>
5031 + 2 * 3 + 4
504</pre>
505
506は次のように解析される:
507
508<pre>
5091 +(2 *(3)) +(4)
510</pre>
511
512ユーザ定義の演算子 (標準の演算子名は使えない) は、常に左から右に動作する。
513
514<a name="Syntax-Assignment"></a>
515<h3>代入</h3>
516
517Io は3つの代入演算子を持つ:
518
519<p>
520<table cellpadding=2 cellspacing=0 border=0 style="margin-left:1em">
521<tr>
522<td style="width:5em">
523<b><i>operator</i></b> 
524</td>
525<td>
526<b><i>action</i></b>
527</td>
528</tr>
529
530<tr>
531<td>
532<i>::=</i>
533</td>
534<td>
535<i>スロットの生成, setter の生成, 値の代入</i>
536</td>
537</tr>
538
539<tr>
540<td>
541<i>:=</i>
542</td>
543<td>
544<i>スロットの生成, 値の代入</i>
545</td>
546</tr>
547
548<tr>
549<td>
550<i>=</i>
551</td>
552<td>
553<i>スロットが存在すれば値の代入、もしなければ例外を発生する</i>
554</td>
555</tr>
556
557</table>
558<p>
559
560These operators are compiled to normal messages whose methods can be overridden. 例:
561
562
563<p>
564<table cellpadding=2 cellspacing=0 border=0 style="margin-left:1em">
565<tr>
566<td style="width:5em">
567<b><i>source</i></b>    
568</td>
569<td>
570<b><i>compiles to</i></b>
571</td>
572</tr>
573
574<tr>
575<td>
576<i>a ::= 1</i>
577</td>
578<td>
579<i>newSlot("a", 1)</i>
580</td>
581</tr>
582
583<tr>
584<td>
585<i>a := 1</i>
586</td>
587<td>
588<i>setSlot("a", 1)</i>
589</td>
590</tr>
591
592<tr>
593<td>
594<i>a = 1</i>
595</td>
596<td>
597<i>updateSlot("a", 1)</i>
598</td>
599</tr>
600
601</table>
602<p>
603       
604On Locals objects, updateSlot is overridden so it will update the slot in the object in which the method was activated if the slot is not found the locals. This is done so update assignments in methods don't require self to be an explicit target.
605
606<a name="Syntax-Numbers"></a>
607<h3>数値</h3>
608
609以下は、有効な数値フォーマットの例です:
610
611<pre>
612123
613123.456
6140.456
615.456
616123e-4
617123e4
618123.456e-7
619123.456e2
620</pre>
621
62216進数もサポートされます(どんなケースでも):
623
624<pre>
6250x0
6260x0F
6270XeE
628</pre>
629
630<a name="Syntax-Strings"></a>
631<h3>文字列</h3>
632
633Strings can be defined surrounded by a single set of double quotes with escaped quotes (and other escape characters) within.
634
635<pre>
636s := "this is a \"test\".\nThis is only a test."
637</pre>
638
639Or for strings with non-escaped characters and/or spanning many lines, triple quotes can be used.
640
641<pre>
642s := """this is a "test".
643This is only a test."""
644</pre>
645
646<a name="Syntax-Comments"></a>
647<h3>コメント</h3>
648
649コメントには //, /**/ と # のスタイルをサポートしています。
650
651<pre>
652a := b // add a comment to a line
653
654/* comment out a group
655a := 1
656b := 2
657*/
658</pre>
659
660"#" スタイルは Unix でのスクリプトに役立ちます:
661
662<pre>
663#!/usr/local/bin/io
664</pre>
665
666貴方は Io の文法について知るために必要なこと全てを知っている。 制御構造・オブジェクト・メソッド・例外は 上記で説明した構文で表現されます。
667
668
669</div>
670<h2>オブジェクト<a name="Objects"></a></h2>
671<div class=indent>
672
673<div class=quote>
674In all other languages we've considered [Fortran, Algol60, Lisp, APL, Cobol, Pascal], a program consists of passive data-objects on the one hand and the executable program that manipulates these passive objects on the other. Object-oriented programs replace this bipartite structure with a homogeneous one: they consist of a set of data systems, each of which is capable of operating on itself. <br>
675- David Gelernter and Suresh J Jag
676</div>
677
678<a name="Objects-Overview"></a>
679<h3>概略</h3>
680
681Io's guiding design principle is simplicity and power through conceptual unification.
682<p>
683
684<table cellpadding=2 cellspacing=0 border=0 style="margin-left:1em">
685<tr>
686<td style="width:15em">
687<b><i>concept</i></b>  
688</td>
689<td>
690<b><i>unifies</i></b>
691</td>
692</tr>
693
694<tr>
695<td>
696<i>blocks with assignable scope </i>
697</td>
698<td>
699<i>functions, methods, closures, functions</i>
700</td>
701</tr>
702
703<tr>
704<td>
705<i>prototypes</i>
706</td>
707<td>
708<i>objects, classes, namespaces, locals</i>
709</td>
710</tr>
711 
712<tr>
713<td valign=top>
714<i>messages</i>
715</td>
716<td>
717<i>operators, calls, assignment, variable accesses</i>
718</td>
719</tr>
720</table>
721
722<a name="Objects-Prototypes"></a>
723<h3>プロトタイプ</h3>
724
725In Io, everything is an object (including the locals storage of a block and the namespace itself) and all actions are messages (including assignment). Objects are composed of a list of key/value pairs called slots, and an internal list of objects from which it inherits called protos. A slot's key is a symbol (a unique immutable sequence) and its value can be any type of object.
726 
727clone and init
728New objects are made by cloning existing ones. A clone is an empty object that has the parent in its list of protos. A new instance's init slot will be activated which gives the object a chance to initialize itself. Like NewtonScript[3], slots in Io are create-on-write.
729
730<pre>
731me := Person clone
732</pre>
733
734To add an instance variable or method, simply set it:
735
736<pre>
737myDog name := "rover"
738myDog sit := method("I'm sitting\n" print)
739</pre>
740
741When an object is cloned, its "init" slot will be called if it has one.
742
743<a name="Objects-Inheritance"></a>
744<h3>継承</h3>
745
746When an object receives a message it looks for a matching slot, if not found, the lookup continues depth first recursively in its protos. Lookup loops are detected (at runtime) and avoided. If the matching slot contains an activatable object, such as a Block or CFunction, it is activated, if it contains any other type of value it returns the value. Io has no globals and the root object in the Io namespace is called the Lobby.
747<p>
748Since there are no classes, there's no difference between a subclass and an instance. Here's an example of creating a the equivalent of a subclass:
749
750<pre>
751Io> Dog := Object clone
752==> Object_0x4a7c0
753</pre>
754
755The above code sets the Lobby slot "Dog" to a clone of the Object object. Notice it only contains a protos list contains a reference to Object. Dog is now essentially a subclass of Object. Instance variables and methods are inherited from the proto. If a slot is set, it creates a new slot in our object instead of changing the proto:
756
757<pre>
758  Io> Dog color := "red"
759  Io> Dog
760  ==> Object_0x4a7c0:
761    color := "red"
762</pre>
763
764<h4>多重継承</h4>
765
766You can add any number of protos to an object's protos list. When responding to a message, the lookup mechanism does a depth first search of the proto chain.
767
768<a name="Objects-Methods"></a>
769<h3>メソッド</h3>
770
771A method is an anonymous function which, when called, creates an object to store its locals and sets the local's proto pointer and its self slot to the target of the message. The Object method method() can be used to create methods. 例:
772
773<pre>
774method((2 + 2) print)
775</pre>
776
777オブジェクト内のメソッドを使用する例:
778
779<pre>
780Dog := Object clone
781Dog bark := method("woof!" print)
782</pre>
783
784The above code creates a new "subclass" of object named Dog and adds a bark slot containing a block that prints "woof!". メソッドを呼び出す例:
785
786<pre>
787Dog bark
788</pre>
789
790The default return value of a block is the  result of the last expression.
791
792<h4>引数</h4>
793
794メソッドは引数をとるようにも定義できる。 例:
795
796<pre>
797add := method(a, b, a + b)
798</pre>
799
800一般的な形式:
801
802<pre><i>
803method(&lt;arg name 0&gt;, &lt;arg name 1&gt;, ..., &lt;do message&gt;)
804</i></pre>
805
806<a name="Objects-Blocks"></a>
807<h3>ブロック</h3>
808
809A block is the same as a method except it is lexically scoped. That is, variable lookups continue in the context of where the block was created instead of the target of the message which activated the block. A block can be created using the Object method block(). ブロックを生成する例:
810
811<pre>
812b := block(a, a + b)
813</pre>
814
815<h4>Blocks vs. メソッド</h4>
816
817This is sometimes a source of confusion so it's worth explaining in detail. Both methods and blocks create an object to hold their locals when they are called. 違いは、ローカル領域のオブジェクト "proto" と "self" に何がセットされるかです。 メソッドでは、それらのスロットには、メッセージのターゲットがセットされる。 ブロックでは、そのブロックが作り出されたときのローカル領域オブジェクトがセットされる。 従ってブロック中では、ローカル領域にない変数は、そのブロックが作成されたときのローカル領域を辿って検索される。 そしてメソッド中では、ローカル領域にない変数は、そのメソッドを呼び出したオブジェクトを辿って検索される。
818
819<h4>call and self slots</h4>
820
821When a locals object is created, its self slot is set (to the target of the message, in the case of a method, or to the creation context, in the case of a block) and its call slot is set to a Call object that can be used to access information about the block activation:
822
823<p>
824<table cellpadding=2 cellspacing=0 border=0 style="margin-left:1em">
825<tr>
826<td style="width:10em">
827<b><i>slot</i></b>
828</td><td>
829<b><i>returns</i></b>
830</td>
831</tr>
832<tr>
833<td>
834<i>call sender </i>
835</td><td>
836<i>locals object of caller</i>
837</td>
838</tr>
839<tr>
840<td>
841<i>call message </i>
842</td><td>
843<i>message used to call this method/block</i>
844</td>
845</tr>
846<tr>
847<td>
848<i>call activated</i>
849</td><td>
850<i>the activated method/block</i>
851</td>
852</tr>
853<tr>
854<td>
855<i>call slotContext</i>
856</td><td>
857<i>context in which slot was found</i>
858</td>
859</tr>
860<tr>
861<td>
862<i>call target</i>
863</td><td>
864<i>current object</i>
865</td>
866</tr>
867</table>
868
869<h4>可変長引数</h4>
870
871The "call message" slot in locals can be used to access the unevaluated argument messages. Example of implementing if() within Io:
872
873<pre>
874myif := method(
875    (call sender doMessage(call message argAt(0))) ifTrue(
876    call sender doMessage(call message argAt(1))) ifFalse(
877    call sender doMessage(call message argAt(2)))
878)
879
880myif(foo == bar, write("true\n"), write("false\n"))
881</pre>
882
883The doMessage() method evaluates the argument in the context of the receiver.
884
885A shorter way to express this is to use the evalArgAt() method on the call object:
886
887<pre>
888myif := method(
889    call evalArgAt(0) ifTrue(
890    call evalArgAt(1)) ifFalse(
891    call evalArgAt(2))
892)
893
894myif(foo == bar, write("true\n"), write("false\n"))
895</pre>
896
897<a name="Objects-Forward"></a>
898<h3>転送</h3>
899
900If an object doesn't respond to a message, it will invoke its "forward" method if it has one. Here's an example of how to print the information related lookup that failed:
901
902<pre>
903MyObject forward := method(
904    write("sender = ", call sender, "\n")
905    write("message name = ", call message name, "\n")
906    args := call message argsEvaluatedIn(call sender)
907    args foreach(i, v, write("arg", i, " = ", v, "\n") )
908)
909</pre>
910
911<a name="Objects-Forward"></a>
912<h3>Resend</h3>
913
914Sends the current message to the receiver's proto with the context of self. 例:
915
916<pre>
917A := Object clone
918A m := method(write("in A\n"))
919B := A clone
920B m := method(write("in B\n"); resend)
921B m
922</pre>
923
924will print:
925
926<pre>
927in B
928in A
929</pre>
930
931For sending other messages to the receiver's proto, super is used.
932
933<a name="Objects-Super"></a>
934<h3>Super</h3>
935
936Sometimes it's necessary to send a message directly to a proto. 例:
937
938<pre>
939Dog := Object clone
940Dog bark := method(writeln("woof!"))
941
942fido := Dog clone
943fido bark := method(
944    writeln("ruf!")
945    super(bark)
946)
947</pre>
948
949Both resend and super are implemented in Io.
950
951<a name="Objects-Introspection"></a>
952<h3>イントロスペクション</h3>
953
954Using the following methods you can introspect the entire Io namespace. There are also methods for modifying any and all of these attributes at runtime.
955
956<h4>slotNames</h4>
957
958The slotNames method returns a list of the names of an object's slots:
959
960<pre>
961Io> Dog slotNames
962==> list("bark")
963</pre>
964
965<h4>protos</h4>
966
967The protos method returns a list of the objects which an object inherits from:
968
969<pre>
970Io> Dog protos
971==> list("Object")
972</pre>
973
974<h4>getSlot</h4>
975
976The "getSlot" method can be used to get the value of a block in a slot without activating it:
977
978<pre>
979myMethod := Dog getSlot("bark")
980</pre>
981
982Above, we've set the locals object's "myMethod" slot to the bark method. It's important to remember that if you then want use the myMethod without activating it, you'll need to use the getSlot method:
983
984<pre>
985otherObject newMethod := getSlot("myMethod")
986</pre>
987
988Here, the target of the getSlot method is the locals object.
989
990<h4>code</h4>
991
992The arguments and expressions of methods are open to introspection. A useful convenience method is "code", which returns a string representation of the source code of the method in a normalized form.
993
994<pre>
995Io> method(a, a * 2) code
996==> "method(a, a *(2))"
997</pre>
998
999</div>
1000<h2>制御構造<a name="Control-Flow"></a></h2>
1001<div class=indent>
1002
1003<a name="Control-Flow-true-false-and-nil"></a>
1004<h3>true, false と nil</h3>
1005
1006Io has predefined singletons for true, false and nil. true and false are used for boolean truth values and nil is typically used to indicate an unset or missing or unavailable value.
1007
1008<a name="Control-Flow-Comparison"></a>
1009<h3>比較</h3>
1010
1011The standard comparison operations (==, !=, >=, <=, >, <) return either the true or false.
1012
1013<pre>
1014Io> 1 < 2
1015==> true
1016</pre>
1017
1018The compare() method is used to implement the compare methods and returns -1, 0 or 1.
1019
1020<a name="Control-Flow-Conditions"></a>
1021<h3>Conditions</h3>
1022
1023<h4>if</h4>
1024
1025The Lobby contains the condition and loop methods. A condition looks like:
1026
1027<pre><i>
1028if(&lt;condition&gt;, &lt;do message&gt;, &lt;else do message&gt;)
1029</i></pre>
1030
1031例:
1032
1033<pre>
1034if(a == 10, "a is 10" print)
1035</pre>
1036
1037The else argument is optional. The condition is considered false if the condition expression evaluates to false or nil, and is considered true otherwise.
1038<p>
1039The result of the evaluated message is returned, so:
1040
1041<pre>
1042if(y < 10, x := y, x := 0)
1043</pre>
1044
1045is the same as:
1046
1047<pre>
1048x := if(y < 10, y, 0)
1049</pre>
1050
1051Conditions can also be used in this form (though not as efficiently):
1052
1053<pre>
1054if(y < 10) then(x := y) else(x := 2)
1055</pre>
1056
1057Else-if is supported:
1058
1059<pre>
1060if(y < 10) then(x := y) elseif(y == 11) then(x := 0) else(x := 2)
1061</pre>
1062
1063As well as Smalltalk style ifTrue, ifFalse, ifNil and ifNonNil methods:
1064
1065<pre>
1066(y < 10) ifTrue(x := y) ifFalse(x := 2)
1067</pre>
1068
1069Notice that the condition expression must have parenthesis surrounding it.
1070
1071<a name="Control-Flow-Loops"></a>
1072<h3>Loops</h3>
1073
1074<h4>loop</h4>
1075
1076The loop method can be used for "infinite" loops:
1077
1078<pre>
1079loop("foo" println)
1080</pre>
1081
1082<h4>while</h4>
1083
1084Like conditions, loops are just messages. while() takes the arguments:
1085
1086<pre><i>
1087while(&lt;condition&gt;, &lt;do message&gt;)
1088</i></pre>
1089
1090例:
1091
1092<pre>
1093a := 1
1094while(a < 10,
1095    a print
1096    a = a + 1
1097)
1098</pre>
1099
1100<h4>for</h4>
1101
1102for() takes the arguments:
1103
1104<pre><i>
1105for(&lt;counter&gt;, &lt;start&gt;, &lt;end&gt;, &lt;optional step&gt;, &lt;do message&gt;)
1106</i></pre>
1107
1108The start and end messages are only evaluated once, when the loop starts.
1109
1110例:
1111
1112<pre>
1113for(a, 0, 10,
1114    a println
1115)
1116</pre>
1117
1118Example with a step:
1119
1120<pre>
1121for(x, 0, 10, 3, x println)
1122</pre>
1123
1124Which would print:
1125
1126<pre>
11270
11283
11296
11309
1131</pre>
1132
1133To reverse the order of the loop, add a negative step:
1134
1135<pre>
1136for(a, 10, 0, -1, a println)
1137</pre>
1138
1139Note: the first value will be the first value of the loop variable and the last will be the last value on the final pass through the loop. So a loop of 1 to 10 will loop 10 times and a loop of 0 to 10 will loop 11 times.
1140
1141Example of using a block in a loop:
1142
1143<pre>
1144test := method(v, v print)
1145for(i, 1, 10, test(i))
1146</pre>
1147
1148<h4>repeat</h4>
1149
1150The Number repeat method is simpler and more efficient when a counter isn't needed.
1151
1152<pre>
11533 repeat("foo" print)
1154==> foofoofoo
1155</pre>
1156
1157<h4>break and continue</h4>
1158
1159The flow control operations break and continue are supported in loops. For example:
1160
1161<pre>
1162for(i, 1, 10,
1163    if(i == 3, continue)
1164    if(i == 7, break)
1165    i print
1166)
1167</pre>
1168
1169出力結果:
1170
1171<pre>
117212456
1173</pre>
1174
1175<h4>return</h4>
1176
1177Any part of a block can return immediately using the return method. Example:
1178
1179<pre>
1180Io> test := method(123 print; return "abc"; 456 print)
1181Io> test
1182123
1183==> abc
1184</pre>
1185
1186</div>
1187<h2>Importing<a name="Importing"></a></h2>
1188<div class=indent>
1189
1190The Importer proto implements Io's built-in auto importer feature. If you put each of your proto's in their own file, and give the file the same name with and ".io" extension, the Importer will automatically import that file when the proto is first referenced. The Importer's default search path is the current working directory, but can add search paths using its addSearchPath() method.
1191
1192</div>
1193<h2>Concurrency<a name="Concurrency"></a></h2>
1194<div class=indent>
1195
1196<a name="Concurrency-Coroutines"></a>
1197<h3>Coroutines</h3>
1198
1199Io uses coroutines (user level cooperative threads), instead of preemptive OS level threads to implement concurrency. This avoids the substantial costs (memory, system calls, locking, caching issues, etc) associated with native threads and allows Io to support a very high level of concurrency with thousands of active threads.
1200
1201<a name="Concurrency-Scheduler"></a>
1202<h3>Scheduler</h3>
1203
1204The Scheduler object is responsible for resuming coroutines that are yielding. The current scheduling system uses a simple first-in-first-out policy with no priorities.
1205
1206<a name="Concurrency-Actors"></a>
1207<h3>Actors</h3>
1208
1209An actor is an object with its own thread (in our case, its own coroutine) which it uses to process its queue of asynchronous messages. Any object in Io can be sent an asynchronous message by placing a @ or @@ before the message name. (think of the "a" in @ as standing for "asynchronous")
1210<p>
1211例:
1212
1213<pre>
1214result := self foo // synchronous
1215futureResult := self @foo // async, immediately returns a Future
1216self @@foo // async, immediately returns nil
1217</pre>
1218
1219When an object receives an asynchronous message it puts the message in its queue and, if it doesn't already have one, starts a coroutine to process the messages in its queue. Queued messages are processed sequentially in a first-in-first-out order. Control can be yielded to other coroutines by calling "yield". Example:
1220
1221<pre>
1222obj1 := Object clone
1223obj1 test := method(for(n, 1, 3, n print; yield))
1224obj2 := obj1 clone
1225obj1 @@test; obj2 @@test
1226while(Scheduler yieldingCoroutines size > 1, yield)
1227</pre>
1228
1229This would print "112233".
1230
1231Here's a more real world example:
1232
1233<pre>
1234HttpServer handleRequest := method(aSocket,
1235    HttpRequestHandler clone @@handleRequest(aSocket)
1236)
1237</pre>
1238
1239<a name="Concurrency-Futures"></a>
1240<h3>Futures</h3>
1241
1242Io's futures are transparent. That is, when the result is ready, they become the result. If a message is sent to a future (besides the two methods it implements), it waits until it turns into the result before processing the message. Transparent futures are powerful because they allow programs minimize blocking while also freeing the programmer from managing the fine details of synchronization.
1243
1244<h4>Auto Deadlock Detection</h4>
1245
1246An advantage of using futures is that when a future requires a wait, it will check to see if pausing to wait for the result would cause a deadlock and if so, avoid the deadlock and raise an exception. It performs this check by traversing the list of connected futures.
1247
1248<h4>The @ and @@ Operators</h4>
1249
1250The @ or @@ before an asynchronous message is just a normal operator message. So:
1251
1252<pre>
1253self @test
1254</pre>
1255
1256Gets parsed as(and can be written as):
1257
1258<pre>
1259self @(test)
1260</pre>
1261
1262<h4>Futures and the Command Line Interface</h4>
1263
1264The command line will attempt to print the result of expressions evaluated in it, so if the result is a Future, it will attempt to print it and this will wait on the result of Future. Example:
1265
1266<pre>
1267Io> q := method(wait(1))
1268Io> @q
1269[1-second delay]
1270==> nil
1271</pre>
1272
1273To avoid this, just make sure the Future isn't the result. Example:
1274
1275<pre>
1276Io> @q; nil
1277[no delay]
1278==> nil
1279</pre>
1280
1281<a name="Concurrency-Yield"></a>
1282<h3>Yield</h3>
1283
1284An object will automatically yield between processing each of its asynchronous messages. The yield method only needs to be called if a yield is required during an asynchronous message execution.
1285
1286<h4>Pause and Resume</h4>
1287
1288It's also possible to pause and resume an object. See the concurrency methods of the Object primitive for details and related methods.
1289
1290</div>
1291<h2>Exceptions<a name="Exceptions"></a></h2>
1292<div class=indent>
1293
1294<a name="Exceptions-Raise"></a>
1295<h3>Raise</h3>
1296
1297An exception can be raised by calling raise() on an exception proto.
1298
1299<pre>
1300Exception raise("generic foo exception")
1301</pre>
1302
1303<!--
1304<pre><i>
1305exceptionProto raise(&lt;description&gt;)
1306</i></pre>
1307
1308There are three predefined children of the Exception proto: Error, Warning and Notification. Examples:
1309
1310<pre>
1311Exception raise("generic foo exception")
1312Warning raise("No defaults found, creating them")
1313Error raise("Not enough memory")
1314</pre>
1315-->
1316
1317<a name="Exceptions-Try-and-Catch"></a>
1318<h3>Try and Catch</h3>
1319
1320To catch an exception, the try() method of the Object proto is used. try() will catch any exceptions that occur within it and return the caught exception or nil if no exception is caught.
1321
1322<pre><i>
1323e := try(&lt;doMessage&gt;)
1324</i></pre>
1325
1326To catch a particular exception, the Exception catch() method can be used. Example:
1327
1328<pre>
1329e := try(
1330    // ...
1331)
1332
1333e catch(Exception,
1334    writeln(e coroutine backtraceString)
1335)
1336</pre>
1337
1338
1339The first argument to catch indicates which types of exceptions will be caught. catch() returns the exception if it doesn't match and nil if it does.
1340
1341<a name="Exceptions-Pass"></a>
1342<h3>Pass</h3>
1343
1344To re-raise an exception caught by try(), use the pass method. This is useful to pass the exception up to the next outer exception handler, usually after all catches failed to match the type of the current exception:
1345
1346<pre>
1347e := try(
1348    // ...
1349)
1350
1351e catch(Error,
1352    // ...
1353) catch(Exception,
1354    // ...
1355) pass
1356</pre>
1357
1358
1359<a name="Exceptions-Custom"></a>
1360<h3>Custom Exceptions</h3>
1361
1362Custom exception types can be implemented by simply cloning an existing Exception type:
1363
1364<pre>
1365MyErrorType := Error clone
1366</pre>
1367
1368</div>
1369<h2>Primitives<a name="Primitives"></a></h2>
1370<div class=indent>
1371
1372Primitives are objects built into Io whose methods are typically implemented in C and store some hidden data in their instances. For example, the Number primitive has a double precision floating point number as its hidden data and its methods that do arithmetic operations are C functions. All Io primitives inherit from the Object prototype and are mutable. That is, their methods can be changed. The reference docs contain more info on primitives.
1373<p>
1374
1375This document is not meant as a reference manual, but an overview of the base primitives and bindings is provided here to give the user a jump start and a feel for what is available and where to look in the reference documentation for further details.
1376
1377<a name="Primitives-Object"></a>
1378<h3>Object</h3>
1379
1380<h4>The ? Operator</h4>
1381
1382Sometimes it's desirable to conditionally call a method only if it exists (to avoid raising an exception). Example:
1383
1384<pre>
1385if(obj getSlot("foo"), obj foo)
1386</pre>
1387
1388Putting a "?" before a message has the same effect:
1389
1390<pre>
1391obj ?foo
1392</pre>
1393
1394<a name="Primitives-List"></a>
1395<h3>List</h3>
1396
1397A List is an array of references and supports all the standard array manipulation and enumeration methods. Examples:
1398<p>
1399空のリストを生成:
1400
1401<pre>
1402a := List clone
1403</pre>
1404
1405list() メソッドを使用することで、任意のリストを生成することができます:
1406
1407<pre>
1408a := list(33, "a")
1409</pre>
1410
1411アイテムの追加:
1412
1413<pre>
1414a append("b")
1415==> list(33, "a", "b")
1416</pre>
1417
1418リストのサイズを取得:
1419
1420<pre>
1421a size
1422==> 3
1423</pre>
1424
1425インデックスを指定し、アイテムの取得(リストのインデックスはゼロから開始されます):
1426
1427<pre>
1428a at(1)
1429==> "a"
1430</pre>
1431
1432Note: List indexes begin at zero and nil is returned if the accessed index doesn't exist.
1433<p>
1434インデックスを指定し、アイテムのセット:
1435
1436<pre>
1437a atPut(2, "foo")
1438==> list(33, "a", "foo", "b")
1439
1440a atPut(6, "Fred")
1441==> Exception: index out of bounds
1442</pre>
1443
1444インデックスを指定し、アイテムの削除:
1445
1446<pre>
1447a remove("foo")
1448==> list(33, "a", "b")
1449</pre>
1450
1451インデックスを指定し、アイテムの挿入:
1452
1453<pre>
1454a atPut(2, "foo")
1455==> list(33, "a", "foo", "56")
1456</pre>
1457
1458<h4>foreach</h4>
1459
1460The foreach, map and select methods can be used in three forms:
1461
1462<pre>
1463Io> a := list(65, 21, 122)
1464</pre>
1465
1466In the first form, the first argument is used as an index variable, the second as a value variable and the 3rd as the expression to evaluate for each value.
1467
1468<pre>
1469Io> a foreach(i, v, write(i, ":", v, ", "))
1470==> 0:65, 1:21, 2:122,
1471</pre>
1472
1473The second form removes the index argument:
1474
1475<pre>
1476Io> a foreach(v, v println)
1477==> 65
147821
1479122
1480</pre>
1481
1482The third form removes the value argument and simply sends the expression as a message to each value:
1483
1484<pre>
1485Io> a foreach(println)
1486==> 65
148721
1488122
1489</pre>
1490
1491<h4>map and select</h4>
1492
1493Io's map and select (known as filter in some other languages) methods allow arbitrary expressions as the map/select predicates.
1494
1495<pre>
1496Io> numbers := list(1, 2, 3, 4, 5, 6)
1497
1498Io> numbers select(isOdd)
1499==> list(1, 3, 5)
1500
1501Io> numbers select(x, x isOdd)
1502==> list(1, 3, 5)
1503
1504Io> numbers select(i, x, x isOdd)
1505==> list(1, 3, 5)
1506
1507Io> numbers map(x, x*2)
1508==> list(2, 4, 6, 8, 10, 12)
1509
1510Io> numbers map(i, x, x+i)
1511==> list(1, 3, 5, 7, 9, 11)
1512
1513Io> numbers map(*3)
1514==> list(3, 6, 9, 12, 15, 18)
1515</pre>
1516
1517The map and select methods return new lists. To do the same operations in-place, you can use selectInPlace() and mapInPlace() methods.
1518
1519<a name="Primitives-Sequence"></a>
1520<h3>Sequence</h3>
1521
1522In Io, an immutable Sequence is called a Symbol and a mutable Sequence is the equivalent of a Buffer or String. Literal strings(ones that appear in source code surrounded by quotes) are Symbols. Mutable operations cannot be performed on Symbols, but one can make mutable copy of a Symbol calling its asMutable method and then perform the mutation operations on the copy.
1523Common string operations
1524Getting the length of a string:
1525
1526<pre>
1527"abc" size
1528==> 3
1529</pre>
1530
1531Checking if a string contains a substring:
1532
1533<pre>
1534"apples" containsSeq("ppl")
1535==> true
1536</pre>
1537
1538Getting the character (byte) at position N:
1539
1540<pre>
1541"Kavi" at(1)
1542==> 97
1543</pre>
1544
1545Slicing:
1546
1547<pre>
1548"Kirikuro" slice(0, 2)
1549==> "Ki"
1550
1551"Kirikuro" slice(-2)  # NOT: slice(-2, 0)!
1552==> "ro"
1553
1554Io> "Kirikuro" slice(0, -2)
1555# "Kiriku"
1556</pre>
1557
1558Stripping whitespace:
1559
1560<pre>
1561"  abc  " adMutable strip
1562==> "abc"
1563
1564"  abc  " asMutable lstrip
1565==> "abc  "
1566
1567"  abc  " asMutable rstrip
1568==> "  abc"
1569</pre>
1570
1571Converting to upper/lowercase:
1572
1573<pre>
1574"Kavi" asUppercase
1575==> "KAVI"
1576"Kavi" asLowercase
1577==> "kavi"
1578</pre>
1579
1580Splitting a string:
1581
1582<pre>
1583"the quick brown fox" split
1584==> list("the", "quick", "brown", "fox")
1585</pre>
1586
1587Splitting by others character is possible as well.
1588
1589<pre>
1590"a few good men" split("e")
1591==> list("a f", "w good m", "n")
1592</pre>
1593
1594Converting to number:
1595
1596<pre>
1597"13" asNumber
1598==> 13
1599
1600"a13" asNumber
1601==> nil
1602</pre>
1603
1604String interpolation:
1605
1606<pre>
1607name := "Fred"
1608==> Fred
1609"My name is #{name}" interpolate
1610==> My name is Fred
1611 </pre>
1612
1613Interpolate will eval anything with #{} as Io code in the local context. The code may include loops or anything else but needs to return an object that responds to asString.
1614
1615<a name="Primitives-Ranges"></a>
1616<h3>Ranges</h3>
1617
1618A range is a container containing a start and an end point, and instructions on how to get from the start, to the end. Using Ranges is often convenient when creating large lists of sequential data as they can be easily converted to lists, or as a replacement for the for() method.
1619
1620<h4>The Range protocol</h4>
1621
1622Each object that can be used in Ranges needs to implement a "nextInSequence" method which takes a single optional argument (the number of items to skip in the sequence of objects), and return the next item after that skip value. The default skip value is 1. The skip value of 0 is undefined. An example:
1623
1624<pre>
1625Number nextInSequence := method(skipVal,
1626    if(skipVal isNil, skipVal = 1)
1627    self + skipVal
1628)
1629</pre>
1630
1631With this method on Number (it's already there in the standard libraries), you can then use Numbers in Ranges, as demonstrated below:
1632
1633<pre>
16341 to(5) foreach(v, v println)
1635</pre>
1636
1637The above will print 1 through 5, each on its own line.
1638
1639<a name="Primitives-File"></a>
1640<h3>File</h3>
1641
1642The methods openForAppending, openForReading, or openForUpdating are used for opening files. To erase an existing file before opening a new open, the remove method can be used. Example:
1643
1644<pre>
1645f := File with("foo.txt)
1646f remove
1647f openForUpdating
1648f write("hello world!")
1649f close
1650</pre>
1651
1652<a name="Primitives-Directory"></a>
1653<h3>Directory</h3>
1654
1655Creating a directory object:
1656
1657<pre>
1658dir := Directory with("/Users/steve/")
1659</pre>
1660
1661Get a list of file objects for all the files in a directory:
1662
1663<pre>
1664files := dir files
1665==> list(File_0x820c40, File_0x820c40, ...)
1666</pre>
1667
1668Get a list of both the file and directory objects in a directory:
1669
1670<pre>
1671items := Directory items
1672==> list(Directory_0x8446b0, File_0x820c40, ...)
1673
1674items at(4) name
1675==> DarkSide-0.0.1 # a directory name
1676</pre>
1677
1678Setting a Directory object to a certain directory and using it:
1679
1680<pre>
1681root := Directory clone setPath("c:/")
1682==> Directory_0x8637b8
1683
1684root fileNames
1685==> list("AUTOEXEC.BAT", "boot.ini", "CONFIG.SYS", ...)
1686</pre>
1687
1688Testing for existence:
1689
1690<pre>
1691Directory clone setPath("q:/") exists
1692==> false
1693</pre>
1694
1695Getthing the current working directory:
1696
1697<pre>
1698Directory currentWorkingDirectory
1699==> "/cygdrive/c/lang/IoFull-Cygwin-2006-04-20"
1700</pre>
1701
1702<a name="Primitives-Date"></a>
1703<h3>Date</h3>
1704
1705Creating a new date instance:
1706
1707<pre>
1708d := Date clone
1709</pre>
1710
1711Setting it to the current date/time:
1712
1713<pre>
1714d now
1715</pre>
1716
1717Getting the date/time as a number, in seconds:
1718
1719<pre>
1720Date now asNumber
1721==> 1147198509.417114
1722
1723Date now asNumber
1724==> 1147198512.33313
1725</pre>
1726
1727Getting individual parts of a Date object:
1728
1729<pre>
1730d := Date now
1731==> 2006-05-09 21:53:03 EST
1732
1733d
1734==> 2006-05-09 21:53:03 EST
1735
1736d year
1737==> 2006
1738
1739d month
1740==> 5
1741
1742d day
1743==> 9
1744
1745d hour
1746==> 21
1747
1748d minute
1749==> 53
1750
1751d second
1752==> 3.747125
1753</pre>
1754
1755Find how long it takes to execute some code:
1756
1757<pre>
1758Date cpuSecondsToRun(100000 repeat(1+1))
1759==> 0.02
1760</pre>
1761
1762<a name="Primitives-Networking"></a>
1763<h3>Networking</h3>
1764
1765All of Io's networking is done with asynchronous sockets underneath, but operations like reading and writing to a socket appear to be synchronous since the calling coroutine is unscheduled until the socket has completed the operation, or a timeout occurs. Note that you'll need to first reference the associated addon in order to cause it to load before using its objects. In these examples, you'll have to reference "Socket" to get the Socket addon to load first.
1766<p>
1767Creating a URL object:
1768
1769<pre>
1770url := URL with("http://example.com/")
1771</pre>
1772
1773Fetching an URL:
1774
1775<pre>
1776data := url fetch 
1777</pre>
1778
1779Streaming a URL to a file:
1780
1781<pre>
1782url streamTo(File with("out.txt"))
1783</pre>
1784
1785A simple whois client:
1786
1787<pre>
1788whois := method(host,
1789    socket := Socket clone setHostName("rs.internic.net") setPort(43)
1790    socket connect streamWrite(host, "\n")
1791    while(socket streamReadNextChunk, nil)
1792    return socket readBuffer
1793)
1794</pre>
1795
1796A minimal web server:
1797
1798<pre>
1799WebRequest := Object clone do(
1800    handleSocket := method(aSocket,
1801        aSocket streamReadNextChunk
1802        request := aSocket readBuffer betweenSeq("GET ", " HTTP")
1803        f := File with(request)
1804        if(f exists, f streamTo(aSocket), aSocket streamWrite("not found"))
1805        aSocket close
1806    )
1807)
1808
1809WebServer := Server clone do(
1810    setPort(8000)
1811    handleSocket := method(aSocket,
1812        WebRequest clone @handleSocket(aSocket)
1813    )
1814)
1815
1816WebServer start
1817</pre>
1818
1819<a name="Primitives-XML"></a>
1820<h3>XML</h3>
1821
1822Using the XML parser to find the links in a web page:
1823
1824<pre>
1825SGML // reference this to load the SGML addon
1826xml := URL with("http://www.yahoo.com/") fetch asXML
1827links := xml elementsWithName("a") map(attributes at("href"))
1828</pre>
1829
1830<a name="Primitives-Vector"></a>
1831<h3>Vector</h3>
1832
1833Io's Vectors are built on its Sequence primitive and are defined as:
1834
1835<pre>
1836Vector := Sequence clone setItemType("float32")
1837</pre>
1838
1839The Sequence primitive supports SIMD acceleration on a number of float32 operations. Currently these include add, subtract, multiple and divide but in the future can be extended to support most math, logic and string manipulation related operations.
1840
1841Here's a small example:
1842
1843<pre>
1844iters := 1000
1845size := 1024
1846ops := iters * size
1847
1848v1 := Vector clone setSize(size) rangeFill
1849v2 := Vector clone setSize(size) rangeFill
1850
1851dt := Date secondsToRun(
1852    iters repeat(v1 *= v2)
1853)
1854
1855writeln((ops/(dt*1000000000)) asString(1, 3), " GFLOPS")
1856</pre>
1857
1858Which when run on 2Ghz Mac Laptop, outputs:
1859
1860<pre>
18611.255 GFLOPS
1862</pre>
1863
1864A similar bit of C code (without SIMD acceleration) outputs:
1865
1866<pre>
18670.479 GFLOPS
1868</pre>
1869
1870So for this example, Io is about three times faster than plain C.
1871
1872<!--
1873</div>
1874<h2>Metaprogramming<a name="Metaprogramming"></a></h2>
1875<div class=indent>
1876
1877</i>forthcoming...
1878
1879Object
1880setIsActivatable
1881forward
1882introspection
1883getSlot, slotSummary, docs, namespaces
1884Block
1885setScope()
1886setPassStops()
1887setDoesCatchStops()
1888doesCatchStops
1889setMessage()
1890Message
1891Manipulating Message Trees
1892setNext()
1893setArgumentNames()
1894setCachedResult()
1895構文
1896squareBrackets()
1897curlyBrackets()
1898operators
1899adding
1900precedence ordering
1901-->
1902
1903</div>
1904<h2>Unicode<a name="Unicode"></a></h2>
1905<div class=indent>
1906
1907<a name="Unicode-Sequences"></a>
1908<h3>Sequences</h3>
1909
1910In Io, symbols, strings, and vectors are unified into a single Sequence prototype which is an array of any available hardware data type such as:
1911 
1912<pre>
1913uint8, uint16, uint32, uint64
1914int8, int16, int32, int64
1915float32, float64
1916</pre>
1917
1918<a name="Unicode-Supported-Encodings"></a>
1919<h3>Supported Encodings</h3>
1920
1921Also, a Sequence has a encoding attribute, which can be:
1922
1923<pre>
1924number, ascii, ucs2, ucs4, utf8
1925</pre>
1926
1927UCS-2 and UCS-4 are the fixed character width versions of UTF-16 and UTF-32, respectively. A String is just a Sequence with a text encoding, a Symbol is an immutable String and a Vector is a Sequence with a number encoding.
1928<p>
1929UTF encodings are assumed to be big endian.
1930<p>
1931Except for input and output, all strings should be kept in a fixed character width encoding. This design allows for a simpler implementation, code sharing between vector and string ops, fast index-based access, and SIMD acceleration of Sequence operations. All Sequence methods will do automatic type conversions as needed.
1932
1933<a name="Unicode-Source"></a>
1934<h3>Source</h3>
1935
1936Io source files are assumed to be in UTF8 (of which ASCII is a subset). When a source file is read, it s symbols and strings are stored in Sequences in their minimal fixed character width encoding. Examples:
1937
1938<pre>
1939Io> "hello" encoding
1940==> ascii
1941
1942Io> "π" encoding
1943==> ucs2
1944
1945Io> "∞" encoding
1946==> ucs2
1947</pre>
1948
1949
1950
1951We can also inspect the internal representation:
1952
1953<pre>
1954Io> "π" itemType
1955==> uint16
1956
1957Io> "π" itemSize
1958==> 2
1959</pre>
1960
1961<a name="Unicode-Conversion"></a>
1962<h3>Conversion</h3>
1963
1964The Sequence object has a number of conversion methods:
1965
1966<pre>
1967asUTF8
1968asUCS2
1969asUCS4
1970</pre>
1971
1972
1973</div>
1974<h2>Embedding<a name="Embedding"></a></h2>
1975<div class=indent>
1976
1977<a name="Embedding-Conventions"></a>
1978<h3>Conventions</h3>
1979
1980Io's C code is written using object oriented style conventions where structures are treated as objects and functions as methods. Familiarity with these may help make the embedding APIs easier to understand.
1981
1982<h4>Structures</h4>
1983
1984Member names are words that begin with a lower case character with successive words each having their first character upper cased. Acronyms are capitalized. Structure names are words with their first character capitalized.
1985
1986例:
1987
1988<pre>
1989typdef struct
1990{
1991    char *firstName;
1992    char *lastName;
1993    char *address;
1994} Person;
1995</pre>
1996
1997<h4>Functions</h4>
1998
1999Function names begin with the name of structure they operate on followed by an underscore and the method name. Each structure has a new and free function.
2000<p>
2001
2002例:
2003
2004<pre>
2005List *List_new(void);
2006void List_free(List *self);
2007</pre>
2008
2009All methods (except new) have the structure (the "object") as the first argument the variable is named "self". Method names are in keyword format. That is, for each argument, the method name has a description followed by an underscore. The casing of the descriptions follow that of structure member names.
2010<p>
2011例:
2012
2013<pre>
2014int List_count(List *self); /* no argument */
2015void List_add_(List *self, void *item); /* one argument */
2016void Dictionary_key_value_(Dictionary *self, char *key, char *value);
2017</pre>
2018
2019<h4>File Names</h4>
2020
2021Each structure has its own separate .h and .c files. The names of the files are the same as the name of the structure. These files contain all the functions(methods) that operate on the given structure.
2022
2023<a name="Embedding-IoState"></a>
2024<h3>IoState</h3>
2025
2026An IoState can be thought of as an instance of an Io "virtual machine", although "virtual machine" is a less appropriate term because it implies a particular type of implementation.
2027
2028<h4>Multiple states</h4>
2029
2030Io is multi-state, meaning that it is designed to support multiple state instances within the same process. These instances are isolated and share no memory so they can be safely accessed simultaneously by different os threads, though a given state should only be accessed by one os thread at a time.
2031
2032<h4>Creating a state</h4>
2033Here's a simple example of creating a state, evaluating a string in it, and freeing the state:
2034
2035<pre>
2036#include "IoState.h"
2037
2038int main(int argc, const char *argv[])
2039{
2040    IoState *self = IoState_new();
2041    IoState_init(self);
2042    IoState_doCString_(self, "writeln(\"hello world!\"");
2043    IoState_free(self);
2044    return 0;
2045}
2046</pre>
2047
2048<a name="Embedding-Values"></a>
2049<h3>Values</h3>
2050
2051We can also get return values and look at their types and print them:
2052
2053<pre>
2054IoObject *v = IoState_doCString_(self, someString);
2055char *name = IoObject_name(v);
2056printf("return type is a ‘%s', name);
2057IoObject_print(v);
2058</pre>
2059
2060<h4>Checking value types</h4>
2061
2062There are some macro short cuts to help with quick type checks:
2063
2064<pre>
2065if (ISNUMBER(v))
2066{
2067    printf("result is the number %f", IoNumber_asFloat(v));
2068}
2069else if(ISSEQ(v))
2070{
2071    printf("result is the string %s", IoSeq_asCString(v));
2072}
2073else if(ISLIST(v))
2074{
2075    printf("result is a list with %i elements", IoList_rawSize(v));
2076}
2077</pre>
2078
2079Note that return values are always proper Io objects (as all values are objects in Io). You can find the C level methods (functions like IoList_rawSize()) for these objects in the header files in the folder Io/libs/iovm/source.
2080
2081</div>
2082<h2>Bindings<a name="Bindings"></a></h2>
2083<div class=indent>
2084
2085Documentation on how to write bindings/addons forthcoming..
2086
2087</div>
2088<h2>Appendix<a name="Appendix"></a></h2>
2089<div class=indent>
2090
2091<a name="Appendix-Grammar"></a>
2092<h3>Grammar</h3>
2093
2094<h4>messages</h4>
2095<pre>
2096expression ::= { message | sctpad }
2097message ::= [wcpad] symbol [scpad] [arguments]
2098arguments ::= Open [argument [ { Comma argument } ]] Close
2099argument ::= [wcpad] expression [wcpad]
2100symbols
2101symbol ::= Identifier | number | Operator | quote
2102Identifier ::= { letter | digit | "_" }
2103Operator ::= { ":" | "." | "'" | "~" | "!" | "@" | "$" |
2104"%" | "^" | "&" | "*" | "-" | "+" | "/" | "=" | "{" | "}" |
2105"[" | "]" | "|" | "\" | "<" | ">" | "?" }
2106</pre>
2107
2108<h4>quotes</h4>
2109<pre>
2110quote ::= MonoQuote | TriQuote
2111MonoQuote ::= """ [ "\"" | not(""")] """
2112TriQuote ::= """"" [ not(""""")] """""
2113</pre>
2114
2115<h4>spans</h4>
2116<pre>
2117Terminator ::= { [separator] ";" | "\n" | "\r" [separator] }
2118separator ::= { " " | "\f" | "\t" | "\v" }
2119whitespace ::= { " " | "\f" | "\r" | "\t" | "\v" | "\n" }
2120sctpad ::= { separator | Comment | Terminator }
2121scpad ::= { separator | Comment }
2122wcpad ::= { whitespace | Comment }
2123</pre>
2124
2125<h4>comments</h4>
2126<pre>
2127Comment ::= slashStarComment | slashSlashComment | poundComment
2128slashStarComment ::= "/*" [not("*/")] "*/"
2129slashSlashComment ::= "//" [not("\n")] "\n"
2130poundComment ::= "#" [not("\n")] "\n"
2131</pre>
2132
2133<h4>numbers</h4>
2134<pre>
2135number ::= HexNumber | Decimal
2136HexNumber ::= "0" anyCase("x") { [ digit | hexLetter ] }
2137hexLetter ::= "a" | "b" | "c" | "d" | "e" | "f"
2138Decimal ::= digits | "." digits | digits "." digits ["e" [-] digits]
2139</pre>
2140
2141<h4>characters</h4>
2142<pre>
2143Comma ::= ","
2144Open ::= "(" | "[" | "{"
2145Close ::= ")" | "]" | "}"
2146letter ::= "a" ... "z" | "A" ... "Z"
2147digit ::= "0" ... "9"
2148digits ::= { digit }
2149</pre>
2150
2151<a name="Appendix-Credits"></a>
2152<h3>Credits</h3>
2153
2154Io is the product of all the talented folks who taken the time and interest to make a contribution. The complete list of contributors is difficult to keep track of, but some of the recent major contributors include; Jonathan Wright, Jeremy Tregunna, Mike Austin, Chris Double, Rich Collins, Oliver Ansaldi, James Burgess, Baptist Heyman, Ken Kerahone, Christian Thater, Brian Mitchell, Zachary Bir and many more. The mailing list archives, repo inventory and release history are probably the best sources for a more complete record of individual contributions.
2155
2156
2157<a name="Appendix-References"></a>
2158<h3>References</h3>
2159
2160
2161<table cellpadding=0 cellspacing=0 border=0>
2162<tr>
2163<td style="width:3em" valign=top>
21641
2165</td>
2166<td>    
2167Goldberg, A et al. <br>
2168Smalltalk-80: The Language and Its Implementation<br>
2169Addison-Wesley, 1983<br>
2170</td>
2171</tr>
2172
2173<tr><td colspan=2 style="height:1em"></td></tr>
2174
2175<tr>
2176<td valign=top>
21772
2178</td>
2179<td>
2180Ungar, D and Smith, <br>
2181RB. Self: The Power of Simplicity<br>
2182OOPSLA, 1987<br>
2183</td>
2184</tr>
2185
2186<tr><td colspan=2 style="height:1em"></td></tr>
2187
2188<tr>
2189<td valign=top>
21903
2191</td>
2192<td>
2193Smith, W. <br>
2194Class-based NewtonScript Programming<br>
2195PIE Developers magazine, Jan 1994<br>
2196</td>
2197</tr>
2198
2199<tr><td colspan=2 style="height:1em"></td></tr>
2200
2201<tr>
2202<td valign=top>
22034
2204</td>
2205<td>
2206Lieberman <br>
2207H. Concurrent Object-Oriented Programming in Act 1<br>
2208MIT AI Lab, 1987<br>
2209</td>
2210</tr>
2211
2212<tr><td colspan=2 style="height:1em"></td></tr>
2213
2214<tr>
2215<td valign=top>
22165
2217</td>
2218<td>
2219McCarthy, J et al. <br>
2220LISP I programmer's manual <br>
2221MIT Press, 1960 <br>
2222</td>
2223</tr>
2224
2225<tr><td colspan=2 style="height:1em"></td></tr>
2226
2227<tr>
2228<td valign=top>
22296
2230</td>
2231<td>
2232Ierusalimschy, R, et al. <br>   
2233Lua: an extensible extension language <br>
2234John Wiley & Sons, 1996 <br>
2235</td>
2236</tr>
2237</table>
2238
2239<a name="Appendix-License"></a>
2240<h3>License</h3>
2241
2242Copyright 2006, 2007, 2008 Steve Dekorte. All rights reserved.
2243<p>
2244Redistribution and use of this document with or without modification, are permitted provided that the copies reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
2245<p>
2246This documentation is provided "as is" and any express or implied warranties, including, but not limited to, the implied warranties of merchantability and fitness for a particular purpose are disclaimed. In no event shall the authors be liable for any direct, indirect, incidental, special, exemplary, or consequential damages (including, but not limited to, procurement of substitute goods or services; loss of use, data, or profits; or business interruption) however caused and on any theory of liability, whether in contract, strict liability, or tort (including negligence or otherwise) arising in any way out of the use of this documentation, even if advised of the possibility of such damage.
2247
2248</div>
2249<p><br><br><br>
Note: See TracBrowser for help on using the browser.