//a side-by-side reference sheet//
[#grammar-invocation grammar and invocation] | [#var-expr variables and expression] | [#arithmetic-logic arithmetic and logic] | [#strings strings] | [#regexes regexes] | [#dates-time dates and time] | [#arrays arrays] | [#dictionaries dictionaries] | [#functions functions] | [#execution-control execution control] | [#exceptions exceptions] | [#streams streams] | [#files files] | [#file-fmt file formats] | [#directories directories] | [#processes-environment processes and environment] | [#libraries-namespaces libraries and namespaces] | [#objects objects] | [#inheritance-polymorphism inheritance and polymorphism] | [#reflection reflection] | [#gui gui] | [#net-web net and web]
||~ # general||~ [#javascript javascript]||~ [#smalltalk smalltalk]||~ [#tcl tcl]||~ [#autohotkey autohotkey]|| ||# version-used[#version-used-note version used] _ @< >@||##gray|//ECMAScript 5//##||##gray|//Pharo 3.0//##||##gray|//8.5//##||##gray|//1.1//##|| ||# show-version[#show-version-note show version] _ @< >@||[http://kangax.github.io/compat-table/es5/ ECMAScript 5 compatibility]||SmalltalkImage current aboutThisSystem. _ _ ##gray|//at command line://## _ $ ./pharo Pharo.image printVersion||$ tclsh _ % info tclversion||msgbox % a_ahkversion|| ||||||||||~ # grammar-invocation[#grammar-invocation-note grammar and invocation]|| ||~ ||~ [#javascript javascript]||~ [#smalltalk smalltalk]||~ [#tcl tcl]||~ [#autohotkey autohotkey]|| ||# interpreter[#interpreter-note interpreter] _ @< >@|| || ||$ tclsh foo.tcl||@@>@@ autohotkey foo.ahk|| ||# repl[#repl-note repl] _ @< >@||##gray|//Javascript Console:// _ _ @< >@Chrome (Mac): ⌥⌘J _ @< >@Chrome (Win): Ctrl+Shift+J _ @< >@Firefox (Mac): ⌥⌘K _ @< >@Firefox (Win): Ctrl+Shift+K##|| ||$ tclsh|| || ||# cmd-line-program[#cmd-line-program-note command line program] _ @< >@|| ||$ Pharo @@–@@headless Pharo.image eval ‘1 + 1.’||##gray|//none//##||##gray|//none//##|| ||# stmt-separator[#stmt-separator-note statement separator]||##gray|//; or newline _ _ newline not separator inside (), [], {}, ““, ‘‘, or after binary operator _ _ newline sometimes not separator when following line would not parse as a valid statement//##||##gray|//period://## .||##gray|//newline or// ;## _ _ ##gray|//newline not a separator inside {}, ““, [] or after backslash: \//##||##gray|//sometimes newline//## _ _ ##gray|//newline does not terminate statement: _ _ @< >@(1) inside parens _ @< >@(2) when following line starts with binary operator//##|| ||# block-delimiters[#block-delimiters-note block delimiters] _ @< >@||{}||[ ]||{} ##gray|//or//## ““||{ }|| ||# local-scope-regions[#local-scope-regions-note regions which define lexical scope]||##gray|//top level: _ @< >@html page _ _ nestable: _ @< >@function//##|| || || || ||# expr-stmt[#expr-stmt-note are expressions statements] _ @< >@|| ||##gray|//yes//##||##gray|//no//##||##gray|//no//##|| ||# eol-comment[#eol-comment-note end-of-line comment] _ @< >@||##gray|@@//@@ comment##||##gray|//no//##||##gray|# comment##||; ##gray|//comment//##|| ||# multiple-line-comment[#multiple-line-comment-note multiple line comment]||##gray|/* line _ another line /##||”##gray|//comment _ another comment//##”||if (0) { _ @< >@##gray|//commented out//## _ @< >@##gray|//can contain {} if balanced//## _ }||/ _ ##gray|//comment//## _ ##gray|//another comment//## _ */|| ||||||||||~ # var-expr[#var-expr-note variables and expressions]|| ||~ ||~ [#javascript javascript]||~ [#smalltalk smalltalk]||~ [#tcl tcl]||~ [#autohotkey autohotkey]|| ||# local-var[#local-var-note local variable]||var x = 1; _ _ var y = 2, z = 3;|| ||##gray|# set variable inside procedure:## _ proc foo {##gray|//args//##} { _ @< >@set x 1 _ @< >@##gray|//…//## _ }|| || ||# global-var[#global-var-note global variable]||##gray|@@//@@ assign without using var## _ g = 1; _ _ function incr_global () { g++; }|| ||##gray|# set variable outside procedure:## _ set g 1 _ _ proc incr_global {} { _ @< >@global g _ @< >@incr g _ }|| || ||# assignment[#assignment-note assignment]||x = 1;||a := 1.||set x 1||s1 := PATH _ s2 := “foo bar” _ _ ##gray|; traditional style:## _ s1 = %PATH% _ s2 = foo bar|| ||# parallel-assignment[#parallel-assignment-note parallel assignment] _ @< >@||##gray|//none//##||##gray|//none//##||lassign {1 2 3} x y z _ _ ##gray|# 3 is discarded:## _ lassign {1 2 3} x y _ _ ##gray|# z is set to ““:## _ lassign {1 2} x y z||##gray|//none//##|| ||# swap[#swap-note swap] _ @< >@||tmp = x; _ x = y; _ y = tmp;|| ||lassign “$x $y” y x||##gray|//none//##|| ||# compound-assignment[#compound-assignment-note compound assignment] _ ##gray|//arithmetic, string, bit//##||+= -= *= /= ##gray|//none//## %= _ += _ ##gray|//none//## _ @@<<= >>= @@&= |= ^=|| || ||+= -= *= /= @@//@@= _ .= _ @@<<= >>=@@ &= |= ^=|| ||# incr-decr[#incr-decr-note increment and decrement]||var x = 1; _ var y = ++x; _ var z = @@–@@y;|| || ||##gray|//premodifiers://## _ ++i @@–@@i _ _ ##gray|//postmodifiers://## _ i++ i@@–@@|| ||# var-decl[#var-decl-note variable declaration] _ @< >@|| || || || || ||# null[#null-note null] _ @< >@||null||nil||””||””|| ||# null-test[#null-test-note null test] _ @< >@||v === null||v = nil||v eq ““||v == ““ _ _ ##gray|; traditional style:## _ v =|| ||# undef-var[#undef-var-note undefined variable] _ @< >@||undefined||##gray|//evaluates as// nil##||##gray|//error//##||##gray|//evaluates as empty string//##|| ||# conditional-expr[#conditional-expr-note conditional expression] _ @< >@||x > 0 ? x : -x||x > 0 ifTrue: [x] ifFalse: [0 - x]||expr $x > 0 ? $x : -$x||x > 0 ? x : -x|| ||||||||||~ # arithmetic-logic[#arithmetic-logic-note arithmetic and logic]|| ||~ ||~ [#javascript javascript]||~ [#smalltalk smalltalk]||~ [#tcl tcl]||~ [#autohotkey autohotkey]|| ||# true-false[#true-false-note true and false] _ @< >@||true false||true false||1 0||1 0 _ _ ##gray|//synonyms://## _ true false|| ||# falsehoods[#falsehoods-note falsehoods]||false null undefined ““ 0 NaN||false||0 “false” “no” _ ##gray|//most strings cause error in boolean context; nonzero numbers are true//##||0 ““|| ||# logical-op[#logical-op-note logical operators] _ @< >@||@@&& ||@@ !||& | not||&& @@||@@ !||and or not _ _ ##gray|//synonyms://## _ @@&& || !@@|| ||# relational-expr[#relational-expr-note relational expression]|| || ||if {$x > 3} {…} _ ##gray|# outside of conditionals use expr:## _ expr $x > 3|| || ||# relational-op[#relational-op-note relational operators] _ @< >@||@@===@@ !== < > >= <= _ _ ##gray|//perform type coercion://## _ @@==@@ !=||@@=@@ ~= > < >= <=||== != > < >= <= _ _ ##gray|# string comparison:## _ eq ne||== != > < >= <= _ _ ##gray|//case insensitive equality://## _ @@=@@|| ||# min-max[#min-max-note min and max]||Math.min(1, 2, 3) _ Math.max(1, 2, 3) _ _ Math.min.apply(Math, [1, 2, 3]) _ Math.max.apply(Math, [1, 2, 3])|| ||expr min(1, 2, 3) _ expr max(1, 2, 3)|| || ||# arith-expr[#arith-expr-note arithmetic expression] _ @< >@|| ||1 + 3 _ _ ##gray|"Binary operators are evaluated left to right. _ This is 20:”## _ 1 + 3 * 5||expr 1 + 3 _ ##gray|# expr not needed in conditionals:## _ if {1 + 3} {##gray|//…//##}||1 + 3|| ||# arith-op[#arith-op-note arithmetic operators] _ ##gray|//addition, subtraction, multiplication, float division, quotient, remainder//##||+ - * / ##gray|//none//## %||+ - * / @@//@@ \||+ - * ##gray|//none//## / %||+ - * / @@//@@ ##gray|//none//## @@@@ _ _ ##gray|//modulo function://## mod(m, n)|| ||# int-dvi[#int-div-node integer division] _ @< >@||Math.floor(x / y)||7 @@//@@ 3||expr $x / $y||7 @@//@@ 3|| ||# int-div-zero[#int-div-zero-note integer division by zero] _ @< >@||##gray|//returns assignable value Infinity, NaN, or -Infinity depending upon whether dividend is positive, zero, or negative. _ _ There are literals for Infinity and NaN.//##||##gray|ZeroDivide //exception//##||##gray|//error//##||##gray|//evaluates to empty string//##|| ||# float-div[#float-div-note float division] _ @< >@||13 / 5||7 / 3 asFloat. _ _ ##gray|"exact rational:”## _ 7 / 3||expr $x * 1.0 / $y||7 / 3|| ||# float-div-zero[#float-div-zero-note float division by zero] _ @< >@||##gray|//same behavior as for integers//##||##gray|ZeroDivide //exception//##||##gray|//returns assignable value// Inf //if dividend is positive and// -Inf //if negative. Raises error if dividend is zero. _ _ There is a literal for// Inf.##||##gray|//evaluates to empty string//##|| ||# power[#power-note power] _ @< >@||Math.pow(2, 32)||2 raisedTo 32||expr 2 @@@@ 32 _ expr pow(2, 32)||2 ** 32|| ||# sqrt[#sqrt-note sqrt] _ @< >@||Math.sqrt(2)||2 sqrt||##purple|expr## sqrt(2)||sqrt(2)|| ||[#sqrt-negative-one sqrt -1] _ @< >@||NaN||##gray|//raises// DomainError##||##gray|//error//##||##gray|//evaluates to empty string//##|| ||[#transcendental-func transcendental functions]||Math.exp Math.log Math.sin Math.cos Math.tan Math.asin Math.acos Math.atan Math.atan2||exp ln _ sin cos tan _ arcSin arcCos arcTan||exp log sin cos tan asin acos atan atan2 _ _ ##gray|# how to use math functions:## _ expr exp(2) _ expr atan2(1, 1) _ ::tcl::mathfunc::exp 2 _ ::tcl::mathfunc::atan2 1 1||exp ln _ sin cos tan _ asin acos atan|| ||# transcendental-const[#transcendental-const-note transcendental constants]||Math.PI _ Math.E||Float pi _ Float e||expr 4 * atan(1) _ expr exp(1)|| || ||[#float-truncation float truncation] _ ##gray|//round towards zero, round to nearest integer, round down, round up//##||##gray|//none//## _ Math.round(3.1) _ Math.floor(3.1) _ Math.ceil(3.1)||3.14 asInteger _ 3.14 rounded _ 3.14 ceiling _ 31.4 floor||expr int(3.1) _ expr round(3.1) _ expr floor(3.1) _ expr ceil(3.1)||##gray|//none//## _ round(3.14) _ floor(3.14) _ ceil(3.14)|| ||# abs-val[#abs-val-note absolute value] _ @< >@||Math.abs(-3)||-7 abs||expr abs(-7)||abs(-7)|| ||[#integer-overflow integer overflow] _ @< >@||##gray|//all numbers are floats//##||##gray|//converted to// LargePositiveInteger //or// LargeNegativeInteger##||##gray|//arbitrary length integers since 8.5//##||##gray|//signed modular arithmetic//##|| ||[#float-overflow float overflow] _ @< >@||Infinity||Float infinity ##gray|//or//## Float infinity negated||##gray|//error//##||##gray|//evaluates to string value such as://## _ 1.#INF00|| ||[#random random integer, uniform float]||Math.floor(Math.random() * 100) _ Math.random()||rnd := Random new. _ _ rnd next. _ (rnd nextInt: 100) - 1.||expr int(rand() * 100) _ expr rand() _ none||##gray|; store results in n and x:## _ random, n, 0, 99 _ random, x, 0.0, 1.0|| ||[#seed-random seed random numbers] _ @< >@||##gray|//none//##||rnd := Random new. _ rnd :seed 17.||expr srand(17)||random, , 17|| ||[#bit-operators bit operators] _ @< >@||@@<< >> & | ^ ~@@||5 bitShift: 1 _ 5 bitShift: -1 _ 5 bitAnd: 1 _ 5 bitOr: 1 _ 5 bitInvert ||@<<< >> & | ^ ~>@||@<<< >> & | ^ ~>@ || ||# binary-octal-hex-literals[#binary-octal-hex-literals-note binary, octal, and hex literals]||##gray|//none//## _ 052 ##gray|@@//@@ deprecated## _ 0x2a|| || || || ||# radix[#radix-note radix] _ ##gray|//convert integer to and from string with radix//##||(42).toString(7) _ ##gray|//??//##|| || || || ||||||||||~ # strings[#strings-note strings]|| ||~ ||~ [#javascript javascript]||~ [#smalltalk smalltalk]||~ [#tcl tcl]||~ [#autohotkey autohotkey]|| ||# str-type[#str-type-note string type] _ @< >@||String|| || || || ||# str-literal[#str-literal-note string literal]||"don’t say "no"” _ ‘don\’t say “no”’||’don’’t say “no”’.||"don’t say "no"” _ {don’t say “no”}||"don’t say ““no”””|| ||# new-line-in-str-literal[#newline-in-str-literal-note newline in literal]||##gray|//yes//##||##gray|//no//## _ _ ##gray|” print newline in Transcript:”## _ Transcript cr.||##gray|//yes//##|| || ||# str-literal-esc[#str-literal-esc-note literal escapes]||##gray|//single and double quotes://## _ \b \f \n \r \t \v \uhhhh \xhh " \’ \||##gray|//none//##||##gray|//in double quotes://## _ \a \b \f \n \r \t \v \ " \oooo \uhhhh \xhh|| || ||# var-interpolation[#var-interpolation-note variable interpolation]||##gray|@@//@@ None; use string concatenation. _ @@//@@ Both of these expressions are ‘11’:## _ 1 + “1” _ “1” + 1|| ||set count 3 _ set item “ball” _ “$count ${item}s”|| || ||# str-concat[#str-concat-note string concatenate]||s = “Hello, “ + “World!”;||’hello, ‘, ‘world’||set s1 “Hello, “ _ set s2 “World!” _ set s $s1$s2||"hello, “ . “world”|| ||# str-replicate[#str-replicate-note string replicate] _ @< >@||var hbar = Array(80).join(“-”);|| ||set hbar [string repeat “-” 80]|| || ||# str-join[#str-join-note string join] _ @< >@||[“do”, “re”, “mi”].join(“ “)|| ||join [list “do” “re” “mi”] “ “|| || ||# split[#split-note split] _ @< >@||##gray|@@//@@ [ “do”, “re”, ““, “mi”, ““ ]:## _ “do re@< >@mi “.split(“ “) _ _ ##gray|@@//@@ [ “do”, “re”, “mi”, ““ ]:## _ “do re@< >@mi “.split(/\s+/)|| ||split “do re mi”|| || ||# fmt-str[#fmt-str-note format string]||##gray|@@//@@ None; use string concatenation. _ @@//@@ Evaluates to “12.35”:## _ 12.3456.toFixed(2)|| ||set fmt “lorem %s %d %.2f” _ format $fmt “ipsum” 13 3.7|| || ||# translate-case[#translate-case-note translate case] _ ##gray|//to upper, to lower//##||"lorem”.toUpperCase() _ “LOREM”.toLowerCase()||’hello’ asUppercase _ ‘HELLO’ asLowercase||string toupper “lorem” _ string tolower “LOREM”||s1 := “Hello” _ stringupper, s2, s1 _ stringlower, s3, s2|| ||# trim[#trim-note trim]||” lorem “.trim() _ ##gray|# some browsers:## _ “ lorem”.trimLeft() _ “lorem “.trimRight()|| ||string trim “ lorem “ _ string trimleft “ lorem” _ string trimright “lorem “|| || ||# pad[#pad-note pad]||##gray|//none//##|| ||format “%10s” “lorem” _ format “%-10s” “lorem”|| || ||# str-to-num[#str-to-num-note string to number]||7 + parseInt(“12”, 10) _ 73.9 + parseFloat(“.037”) _ _ ##gray|@@//@@ 12:## _ parseInt(“12A”) _ ##gray|@@//@@ NaN:## _ parseInt(“A”)||12’ asInteger + 7||##gray|# use expr to interpret as numbers:## _ set x “12” _ expr 7 + $x _ set y “.037” _ expr 73.9 + $y|| || ||# num-to-str[#num-to-str-note number to string] _ @< >@||"value: “ + 8||7 printString, ‘ items’||##gray|//all values are strings//##|| || ||# prefix-suffix-test[#prefix-suffix-test-note prefix and suffix test]||"foobar”.startsWith(“foo”) _ “foobar”.endsWith(“bar”)|| || || || ||# str-len[#str-len-note length] _ @< >@||"lorem”.length||’hello’ byteSize||string length “lorem”||strlen(“hello”)|| ||# index-substr[#index-substr-note index of substring]||##gray|@@//@@ returns -1 if not found:## _ “lorem ipsum”.indexOf(“ipsum”)||’foo bar’ indexOfAnyOf: ‘bar’||string first “ipsum” “lorem ipsum”||##gray|; returns 5:## _ instr(“foo bar”, “bar”)|| ||# extract-substr[#extract-substr-note extract substring]||"lorem ipsum”.substr(6, 5) _ “lorem ipsum”.substring(6, 11)||’foo bar’ copyFrom: 5 to: 7||string range “lorem ipsum” 6 10||substr(“foo bar”, 5, 3)|| ||# char-literal[#char-literal-note character literal]|| ||$A|| || || ||# lookup-char[#lookup-char-note character lookup]||"lorem ipsum”[6]|| || || || ||# chr-ord[#chr-ord-note chr and ord]||String.fromCharCode(65) _ “A”.charCodeAt(0)||65 asCharacter _ $A asciiValue||format %c 65 _ scan A %c ascii_value|| || ||# str-to-char-array[#str-to-char-array-note to array of characters]||"abcd”.split(““)|| ||split “abcd” ““|| || ||||||||||~ # regexes[#regex-note regular expressions]|| ||~ ||~ [#javascript javascript]||~ [#smalltalk smalltalk]||~ [#tcl tcl]||~ [#autohotkey autohotkey]|| ||# regex-match[#regex-match-note regex match]||if (s.match(/1999/)) { _ @< >@alert(“party!”); _ }|| ||if [regexp @@–@@ {1999} $s] { _ @< >@puts “party!” _ }|| || ||# regex-literal[#regex-literal-note literal, custom delimited literal]||/lorem|ipsum/|| || || || ||# char-class-abbrev[#char-class-abbrev-note character class abbreviations and anchors]||. \d \D \s \S \w \W|| ||##gray|//char class abbrevs://## _ . \d \D \s \S \w \W _ _ ##gray|//anchors://## ^ $ \A \m \M \y \Y \Z|| || ||# regex-anchors[#regex-anchors-note anchors]||^ $ \b \B|| || || || ||# case-insensitive-regex[#case-insensitive-regex-note case insensitive match test]||"Lorem”.match(/lorem/i)|| ||regexp -nocase @@–@@ {lorem} “Lorem”|| || ||# regex-modifiers[#regex-modifiers-note modifiers]||g i m|| ||-all -expanded -indices -inline _ -line -lineanchor -linestop -nocase|| || ||# subst[#subst-note substitution]||s = “do re mi mi mi”; _ s.replace(/mi/g, “ma”);|| ||set s “do re mi mi mi” _ regsub -all @@–@@ “mi” $s “ma”|| || ||# match-prematch-postmatch[#match-prematch-postmatch-note match, prematch, postmatch]||##per|m## = /\d{4}/.exec(s); _ if (m) { _ @< >@match = m[0]; _ @< >@##gray|# no prematch or postmatch## _ }|| || || || ||# group-capture[#group-capture-note group capture]||rx = /^(\d{4})-(\d{2})-(\d{2})$/; _ m = rx.exec(‘2009-06-03’); _ yr = m[1]; _ mo = m[2]; _ dy = m[3];|| ||set s “2009-06-03” _ set rx {^(\d{4})-(\d{2})-(\d{2})$} _ regexp @@–@@ $rx $s - yr mo dy|| || ||# named-grouped-capture[#named-group-capture-note named group capture]|| || || || || ||# scan[#scan-note scan]||var a = “dolor sit amet”.match(/\w+/g);|| || || || ||# backreference[#backreference-note backreference] _ ##gray|//in regex, in substitution string//##||/(\w+) \1/.exec(“do do”) _ _ “do re”.replace(/(\w+) (\w+)/, ‘$2 $1’)|| ||regexp @@–@@ {(\w+) \1} “do do” _ _ set rx {(\w+) (\w+)} _ regsub -all @@–@@ $rx “do re” {\2 \1}|| || ||||||||||~ # dates-time[#dates-time-note dates and time]|| ||~ ||~ [#javascript javascript]||~ [#smalltalk smalltalk]||~ [#tcl tcl]||~ [#autohotkey autohotkey]|| ||# broken-down-datetime-type[#broken-down-datetime-type-note broken-down datetime type] _ @< >@||Date|| || || || ||# current-datetime[#current-datetime-note current date/time]||var t = new Date();||Date today. _ Time now.||set t [clock seconds]|| || ||# unix-epoch[#unix-epoch-note to unix epoch, from unix epoch]||Math.round(t.getTime() / 1000) _ _ var epoch = 1315716177; _ var t2 = new Date(epoch * 1000);|| ||t _ set t2 1315716177|| || ||# current-unix-epoch[#current-unix-epoch-note current unix epoch]||(##purple|new## ##green|Date##()).getTime() / 1000|| || || || ||# strftime[#strftime-note strftime]|| || ||set fmt “%Y-%m-%d %H:%M:%S” _ clock format $t -format $fmt|| || ||# strptime[#strptime-note strptime]|| || ||##gray|//none//##|| || ||# parse-date[#parse-date-note parse date w/o format]||var t = new Date(“July 7, 1999”);|| ||set t [clock scan “July 7, 1999”]|| || ||# get-date-parts[#get-date-parts-note get date parts]||t.getFullYear() _ t.getMonth() + 1 _ t.getDate() ##gray|@@//@@ getDay() is day of week##|| ||clock format $t -format “%Y” _ clock format $t -format “%m” _ clock format $t -format “%d”|| || ||# get-time-parts[#get-time-parts-note get time parts]||t.getHours() _ t.getMinutes() _ t.getSeconds()|| ||clock format $t -format “%H” _ clock format $t -format “%M” _ clock format $t -format “%S”|| || ||# date-from-parts[#date-from-parts-note build date/time from parts]||var yr = 1999; _ var mo = 9; _ var dy = 10; _ var hr = 23; _ var mi = 30; _ var ss = 0; _ var t = new Date(yr, mo - 1, dy, hr, mi, ss);|| ||##gray|//none//##|| || ||# date-subtraction[#date-subtraction-note result of date subtraction]||##gray|//number containing time difference in milliseconds//##|| || || || ||# add-time-duration[#add-time-duration-note add time duration]||var t1 = new Date(); _ var delta = (10 * 60 + 3) * 1000; _ var t2 = new Date(t1.getTime() + delta);|| || || || ||# local-tmz[#local-tmz-note local timezone]|| || || || || ||# tmz-offset[#tmz-offset-note timezone name; offset from UTC; is daylight savings?]|| || || || || ||# microseconds[#microseconds-note microseconds]|| || || || || ||# sleep[#sleep-note sleep] _ @< >@||##gray|//none//##|| ||after 500|| || ||# timeout[#timeout-note timeout]|| || || || || ||||||||||~ # arrays[#arrays-note arrays]|| ||~ ||~ [#javascript javascript]||~ [#smalltalk smalltalk]||~ [#tcl tcl]||~ [#autohotkey autohotkey]|| ||# resizable-array-literal[#resizable-array-literal-note literal]||a = [1, 2, 3, 4]||nums := OrderedCollection new. _ nums add: 1; add: 2; add: 3; add: 4. _ _ ##gray|"creates immutable array:”## _ nums := #(1 2 3 4)||set a [list 1 2 3 4] _ set a {1 2 3 4}|| || ||# resizable-array-size[#resizable-array-size-note size]||a.length||nums size||llength $a|| || ||empty test||##gray|@@//@@ TypeError if a is null or undefined:## _ a.length === 0|| || || || ||# resizable-array-lookup[#resizable-array-lookup-note lookup]||a[0]||nums at: 1||lindex $a 0|| || ||# resizable-array-update[#resizable-array-update-note update]||a[0] = “lorem”|| ||##gray|# provide start and end index: _
of elements to replace:## _
set a [lreplace $a 1 1 “lorem”]|| || ||out-of-bounds behavior||##gray|//returns// undefined##|| ||##gray|//returns// ““##|| || ||index of element _ ##gray|//first and last occurrence//##||##gray|@@//@@ returns -1 if not found:## _ [6, 7, 7, 8].indexOf(7) _ [6, 7, 7, 8].lastIndexOf(7)|| ||lsearch {6 7 7 8} 7 _ lindex [lsearch -all {6 7 7 8} 7] end _ ##gray|# returns -1 if not found##|| || ||[#array-slice slice]||##gray|@@//@@ select 3rd and 4th elements:## _ [“a”, “b”, “c”, “d”].slice(2, 4)||nums copyFrom: 2 to: 3||lrange $a 1 2|| || ||slice to end||[“a”, “b”, “c”, “d”].slice(1)|| ||lrange {"a” “b” “c” “d”} 1 end|| || ||[#array-concatenation concatenation]||a = [1, 2, 3].concat([4, 5, 6]);|| ||set a [concat {1 2 3} {4 5 6}]|| || ||copy||a = [1, 2, [3, 4]]; _ a2 = a; _ a3 = a.slice(0); _ a4 = JSON.parse(JSON.stringify(a));|| || || || ||[#array-back manipulate back of array]||a = [6, 7, 8]; _ a.push(9); _ i = a.pop();||a := OrderedCollection new. _ a add: 6; add: 7; add: 8. _ _ a add: 9. _ a removeLast.||set a {6 7 8} _ lappend a 9 _ set i [lindex $a end] _ set a [lreplace $a end end]|| || ||[#array-front manipulate front of array]||a = [6, 7, 8]; _ a.unshift(5); _ i = a.shift();||a := OrderedCollection new. _ a add: 6; add: 7; add: 8. _ _ a addFirst: 5. _ a removeFirst.||set a {6 7 8} _ set a [concat {5} $a] _ set a [lassign $a i]|| || ||[#array-iteration array iteration]||[1, 2, 3].forEach(function(n) { _ @< >@alert(n); _ });||nums do: [:o| Transcript show: o printString; cr]||foreach i $a { puts $i }|| || ||[#array-reverse reverse]||var a = [1, 2, 3]; _ a.reverse();|| ||set a {1 2 3} _ set a [lreverse $a]|| || ||[#array-sort sort]||var a = [3, 1, 4, 2]; _ a.sort();|| ||set a {3 1 4 2} _ set a [lsort $a]|| || ||dedupe|| || ||lsort -unique {1 2 2 3}|| || ||[#membership membership] _ @< >@|| ||nums includes: 7||expr {7 in $a} _ expr {7 ni $a}|| || ||intersection|| || ||package require struct::set _ _ ::struct::set intersect {1 2} {2 3}|| || ||union|| || ||package require struct::set _ _ ::struct::set union {1 2} {2 3 4}|| || ||relative complement|| || ||package require struct::set _ _ ::struct::set difference {1 2 3} {2}|| || ||[#map map] _ @< >@||##gray|@@//@@ callback gets 3 args: _ @@//@@ value, index, array## _ a.map(function(x) { return x * x })||#(1 2 3) collect: [ :o | o*o ]||package require struct::list _ _ proc sqr {x} {return [expr $x * $x]} _ ::struct::list map {1 2 3} sqr|| || ||[#filter filter] _ @< >@||a.filter(function(x) { return x > 1 })||#(1 2 3) select: [:o | o > 1]||package require struct::list _ _ proc gt1 {x} {return [expr $x > 1]} _ ::struct::list filter {1 2 3} gt1|| || ||[#reduce reduce] _ @< >@||a.reduce(function(m, o) { _ @< >@@< >@return m + o; _ @< >@}, 0)||#(1 2 3) inject: 0 into: [:m :o| m + o]||package require struct::list _ _ ::struct::list fold {1 2 3} 0 _ ::tcl::mathop::+|| || ||[#universal-test universal test] _ @< >@|| ||#(1 2 3 4) allSatisfy: [:o | o even]|| || || ||[#existential-test existential test] _ @< >@||var a = [1, 2, 3, 4]; _ var even = function(x) { _ @< >@return x % 2 == 0; _ }; _ _ a.every(even) _ a.some(even)||#(1 2 3 4) anySatisfy: [:o | o even]|| || || ||||||||||~ # dictionaries[#dictionaries-note dictionaries]|| ||~ ||~ [#javascript javascript]||~ [#smalltalk smalltalk]||~ [#tcl tcl]||~ [#autohotkey autohotkey]|| ||# dict-ctorl[#dict-ctor-note constructor] _ @< >@||d = {"t”: 1, “f”: 0}; _ ##gray|// keys do not need to be quoted if they _ // are a legal JavaScript variable name _ //and not a reserved word##||h := Dictionary new add: ##maroon|’t’##->1; add: ##maroon|’f’##->0; yourself||set d [dict create t 1 f 0]|| || ||# dict-size[#dict-size-note dictionary size] _ @< >@||var size = 0; _ for (var k in d) { _ @< >@if (d.hasOwnProperty(k)) size++; _ }||h size||dict size $d|| || ||# dict-lookup[#dict-lookup-note lookup] _ @< >@||d.t _ d[“t”]|| h at: ##maroon|’t’##||dict get $d t|| || ||# dict-update[#dict-update-note update]||d[“t”] = 2; _ d.t = 2;|| ||dict set d t 2|| || ||# dict-missing-key[#dict-missing-key-note missing key behavior] _ @< >@||var d = {}; _ ##gray|@@//@@ sets s to undefined:## _ var s = d[“lorem”]; _ ##gray|@@//@@ adds key/value pair:## _ d[“lorem”] = “ipsum”; ||##gray|//raises exception//##||##gray|//error//##|| || ||# dict-is-key-present[#dict-is-key-present-note is key present] _ @< >@||d.hasOwnProperty(“t”);|| ||dict exists $d t|| || ||# dict-delete[#dict-delete-note delete]||delete d[“t”]; _ delete d.t;|| ||dict unset d t|| || ||# dict-iter[#dict-iter-note iterate] _ @< >@||for (var k in d) { _ @< >@##gray|//use k or d[k]//## _ }||h keysAndValuesDo: [:k :v| ##gray|//code//## ]||foreach {k v} $d { _ @< >@##gray|//code//## _ }|| || ||# dict-key-val-arrays[#dict-key-val-arrays-note keys and values as arrays]|| ||h keys _ h values|| || || ||||||||||~ # functions[#functions-note functions]|| ||~ ||~ [#javascript javascript]||~ [#smalltalk smalltalk]||~ [#tcl tcl]||~ [#autohotkey autohotkey]|| ||# def-func[#def-func-note define]||function add(x, y) { _ @< >@return x+y; _ }||add := [ :a :b | a + b ]||proc add { x y } { _ @< >@expr $x + $y _ }||add(x, y) { _ @< >@return x + y _ }|| ||# call-func[#call-func-note call]||add(1, 2)||add value: 1 value: 2||##gray|# statement position:## _ add 1 2 _ _ ##gray|# argument position:## _ set a [ add 1 2 ]||x := add(1, 2)|| ||# missing-arg[#missing-arg-note missing argument behavior]||##gray|//set to// undefined##||##gray|//raises// BlockClosure //exception//##||##gray|//error//##||##gray|//error//##|| ||# extra-arg[#extra-arg-note extra argument behavior]||##gray|//ignored//##||##gray|//raises// BlockClosure //exception//##||##gray|//error//##||##gray|//error//##|| ||# default-arg[#default-arg-note default argument]||##gray|//none//##|| ||proc log {x {base 10 }} { ##gray|//…//## }||fapprox(x, y, eps=0.001) { _ @< >@return abs(x - y) < eps _ }|| ||[#named-parameters named parameters]|| || || ||##gray|//none//##|| ||# variadic-func[#variadic-func-note variadic function]||##gray|//args in//## arguments[0], arguments[1], ##gray|//… with number of args in//## arguments.length|| || ##gray|//last arg contains list of remaining values//##|f(args) { _ @< >@return args.maxindex() _ }|| || ||# pass-by-ref[#pass-by-ref-note pass by reference]|| || || ||swap(byref v1, byref v2) { _ @< >@tmp := v1 _ @< >@v1 := v2 _ @< >@v2 := tmp _ }|| ||[#return-value return value]||##gray|Return //arg or// undefined. //If invoked with// new //and// return //value not an object, returns// this.##|| ||return ##gray|//arg or empty string//##||##gray|//argument of// return##|| ||# nested-func[#nested-func-note nested function]|| || ||##gray|//defined when containing function executes; visible outside containing function//##|| || ||# anon-func-literal[#anon-func-literal-note anonymous function literal]||var sqr = function(x) { return xx; }|| ||set sqr @@{{x}@@ {return [expr $x*$x]@@}}@@|| || ||# call-anon-func[#call-anon-func-note call anonymous function] _ @< >@||sqr(2)|| ||apply $sqr 2|| || ||# private-state-func[#private-state-func-note function with private state]||function counter() { _ @< >@counter.i += 1; _ @< >@return counter.i; _ } _ _ counter.i = 0; _ alert(counter());|| || || || ||# closure[#closure-note closure]||function make_counter() { _ @< >@var i = 0; _ _ @< >@return function() { _ @< >@@< >@i += 1; _ @< >@@< >@return i; _ @< >@} _ }|| || || || ||||||||||~ # execution-control[#execution-control-note execution control]|| ||~ ||~ [#javascript javascript]||~ [#smalltalk smalltalk]||~ [#tcl tcl]||~ [#autohotkey autohotkey]|| ||# if[#if-note if]||if (0 == n) { _ @< >@alert(“no hits”); _ } else if (1 == n) { _ @< >@alert(“1 hit”); _ } else { _ @< >@alert(n + “ hits”); _ }||msg := [ :s | Transcript show: s. Transcript cr ] _ _ n = 0 _ ifTrue: [ _ @< >@msg value: ‘no hits’ ] _ ifFalse: [ _ @< >@n = 1 _ @< >@ifTrue: [ _ @< >@@< >@msg value: ‘1 hit’ ] _ @< >@fFalse: [ _ @< >@@< >@msg value: n printString, ‘ hits’ ]].||if { 0 == $n } { _ @< >@puts “no hits” _ } elseif { 1 == $n } { _ @< >@puts “1 hit” _ } else { _ @< >@puts “$n hits” _ }||if (n = 0) { _ @< >@msgbox % “zero hits” _ } _ else if (n = 1) { _ @< >@msgbox % “one hit” _ } _ else { _ @< >@msgbox % n . “ hits” _ }|| ||# switch[#switch-note switch]||switch (n) { _ case 0: _ @< >@alert(“no hits\n”); _ @< >@break; _ case 1: _ @< >@alert(“one hit\n”); _ @< >@break; _ default: _ @< >@alert(n + “ hits\n”); _ }|| || || || ||# while[#while-note while]||while (i < 100) { _ @< >@i += 1; _ }||[ i < 100 ] _ whileTrue: [ _ @< >@i := i + 1 ].||while { $i < 100 } { _ @< >@incr i _ }|| || ||# break-continue[#break-continue-note break/continue]||break continue|| ||break continue||exit 0|| ||# for[#for-note for]||for (var i = 0; i < 10; i++) { _ @< >@alert(i); _ }||1 to: 100 do: [ :i | _ @< >@msg value: i printString ].||for {set i 0} {$i < 10} {incr i} { _ @< >@puts $i _ }|| || ||||||||||~ # exceptions[#exceptions-note exceptions]|| ||~ ||~ [#javascript javascript]||~ [#smalltalk smalltalk]||~ [#tcl tcl]||~ [#autohotkey autohotkey]|| ||# base-exc[#base-exc-note base exception]||##gray|//Any value can be thrown.//##|| || || || ||# predefined-exc[#predefined-exc-note predefined exceptions]||Error _ @< >@EvalError _ @< >@RangeError _ @< >@ReferenceError _ @< >@SyntaxError _ @< >@TypeError _ @< >@URIError|| || || || ||[#raise-exception raise exception]||throw new Error(“bad arg”);||Exception raiseSignal: ‘bam!’.||error “bad arg”|| || ||# catch-all-handler[#catch-all-handler-note catch-all handler] _ @< >@||try { _ @< >@risky(); _ } _ catch (e) { _ @< >@alert(“risky failed: “ + e.message); _ }|| || || || ||[#uncaught-exception uncaught exception behavior]|| || ||##gray|//stderr and exit//##|| || ||# re-raise-exc[#re-raise-exc-note re-raise exception]||try { _ @< >@throw new Error(“bam!”); _ } _ catch (e) { _ @< >@alert(“re-raising@@…@@”); _ @< >@throw e; _ }|| || || || ||# last-exc-global[#last-exc-global-note global variable for last exception]||##gray|//none//##|| || || || ||# def-exc[#def-exc-note define exception]||function Bam(msg) { _ @< >@this.message = msg; _ } _ _ Bam.prototype = new Error;|| || || || ||# handle-exc[#handle-exc-note handle exception]||try { _ @< >@throw new Bam(“bam!”); _ } _ catch (e) { _ @< >@if (e instanceof Bam) { _ @< >@@< >@alert(e.message); _ @< >@} _ @< >@else { _ @< >@@< >@throw e; _ @< >@} _ }||[ o risky ] on: Exception do: [ :ex | _ @< >@Transcript show: ‘risky failed’ ]||catch risky retval _ if { retval != 0 } { _ @< >@@< >@puts “risky failed” _ }|| || ||# finally-block[#finally-block-note finally block] _ @< >@||acquire_resource(); _ try { _ @< >@risky(); _ } _ finally { _ @< >@release_resource(); _ }|| || || || ||||||||||~ # streams[#streams-note streams]|| ||~ ||~ [#javascript javascript]||~ [#smalltalk smalltalk]||~ [#tcl tcl]||~ [#autohotkey autohotkey]|| ||# standard-file-handles[#standard-file-handles-note standard file handles]|| || ||stdin _ stdout _ stderr|| || ||# read-stdin[#read-stdin-note read line from stdin]|| || ||gets stdin line|| || ||end-of-file behavior|| || || || || ||chomp|| || ||string trimright $line “\r\n”|| || ||# print-to-stdout[#print-to-stdout-note write line to stdout]|| || ||puts “Hello, World!”|| || ||write formatted string to stdout|| || || || || ||# open-file[#open-file-note open file for reading]|| || ||set f [open “/tmp/foo”]|| || ||# open-file-write[#open-file-write-note open file for writing]|| || ||set f [open “/tmp/foo” “w”]|| || ||set file handle encoding|| || || || || ||open file for appending|| || || || || ||# close-file[#close-file-note close file] _ @< >@|| || ||close $f|| || ||close file implicitly|| || || || || ||i/o error|| || || || || ||encoding error|| || || || || ||# read-line[#read-line-note read line] _ @< >@|| || ||gets $f|| || ||# file-iter[#file-iter-note iterate over file by line]|| || ||while { [gets $f s] >= 0 } { _ @< >@##gray|//use s//## _ }|| || ||read file into array of strings|| || || || || ||read file into string|| || ||set s [ read $f]|| || ||# write-file[#write-file-note write string] _ @< >@|| || ||puts -nonewline $f “lorem ipsum”|| || ||write line|| || || || || ||# flush-file[#flush-file-note flush file handle]|| || ||flush $f|| || ||end-of-file test|| || || || || ||get and set file handle position|| || || || || ||open temporary file|| || || || || ||in memory file|| || || || || ||||||||||~ # files[#file-note files]|| ||~ ||~ [#javascript javascript]||~ [#smalltalk smalltalk]||~ [#tcl tcl]||~ [#autohotkey autohotkey]|| ||# file-test[#file-test-note file exists test, file regular test]|| || ||file exists “/etc/hosts” _ file isfile “/etc/hosts”|| || ||# file-size[#file-size-note file size]|| || || || || ||# readable-writable-executable[#readable-writable-executable-note is file readable, writable, executable]|| || || || || ||# chmod[#chmod-note set file permissions]|| || ||set s “/tmp/foo” _ file attributes $s -permissions 0755|| || ||last modification time|| || || || || ||# file-cp-rm-mv[#file-cp-rm-mv-note copy file, remove file, rename file]|| || ||file copy “/tmp/foo” “/tmp/bar” _ file delete “/tmp/foo” _ file rename “/tmp/bar” “/tmp/foo”|| || ||create symlink, symlink test, readlink|| || || || || ||# tmpfile[#tmpfile-note generate unused file name]|| || ||set tmp [::fileutil::tempfile foo] _ set f [open $tmp “w”] _ puts $f “lorem ipsum” _ close $f _ puts “tmp file: $tmp”|| || ||||||||||~ # file-fmt[#file-fmt-note file formats]|| ||~ ||~ [#javascript javascript]||~ [#smalltalk smalltalk]||~ [#tcl tcl]||~ [#autohotkey autohotkey]|| ||# parse-json[#parse-json-note parse json]||var s1 = ‘{"t”:1,"f”:0}’; _ var d1 = JSON.parse(s1);|| || || || ||# generate-json[#generate-json-note generate json]||var d2 = {’t’: 1, ‘f’: 0}; _ var s2 = JSON.stringify(d1);|| || || || ||||||||||~ # directories[#directories-note directories]|| ||~ ||~ [#javascript javascript]||~ [#smalltalk smalltalk]||~ [#tcl tcl]||~ [#autohotkey autohotkey]|| ||working directory _ ##gray|//get and set//##|| || || || || ||# build-pathname[#build-pathname-note build pathname]|| || ||file join “/etc” “hosts”|| || ||# dirname-basename[#dirname-basename-note dirname and basename]|| || ||file dirname “/etc/hosts” _ file tail “/etc/hosts”|| || ||absolute pathname|| || || || || ||# dir-iter[#dir-iter-note iterate over directory by file]|| || || || || ||glob paths|| || || || || ||# mkdir[#mkdir-note make directory]|| || ||file mkdir “/tmp/foo/bar”|| || ||recursive copy|| || || || || ||# rmdir[#rmdir-note remove empty directory]|| || ||file delete “/tmp/foodir”|| || ||# rm-rf[#rm-rf-note remove directory and contents]|| || ||file delete -force “/tmp/foodir”|| || ||# dir-test[#dir-test-note directory test] _ @< >@|| || ||file isdirectory “/tmp”|| || ||generate unused directory|| || || || || ||system temporary file directory|| || || || || ||||||||||~ # processes-environment[#processes-environment-note processes and environment]|| ||~ ||~ [#javascript javascript]||~ [#smalltalk smalltalk]||~ [#tcl tcl]||~ [#autohotkey autohotkey]|| ||# cmd-line-arg[#cmd-line-arg-note command line arguments]|| || ||[lindex $argv 0] _ [lindex $argv 1] _ ##gray|//…//##|| || ||# env-var[#env-var-note environment variable] _ ##gray|//get, set//##|| || ||$env(HOME)|| || ||# pid[#pid-note get pid, parent pid]|| || || || || ||# exit[#exit-note exit] _ @< >@|| || ||exit 0|| || ||# external-cmd[#external-cmd-note external command]|| || ||exec ls|| || ||# cmd-subst[#cmd-subst-note command substitution]|| || ||set f [ open |ls ] _ read f|| || ||||||||||~ # libraries-namespaces[#libraries-namespaces-note libraries and namespaces]|| ||~ ||~ [#javascript javascript]||~ [#smalltalk smalltalk]||~ [#tcl tcl]||~ [#autohotkey autohotkey]|| ||# load-lib[#load-lib-note load library]|| || ||source foo.tcl _ add 3 7|| || ||load library in subdirectory|| || || || || ||hot patch|| || || || || ||load error|| || || || || ||main routine in library|| || || || || ||# lib-path[#lib-path-note library path]|| || ||##gray|//none//##|| || ||# lib-path-env[#lib-path-env-note library path environment variable]|| || ||TCLLIBPATH|| || ||library path command line option|| || || || || ||simple global identifiers|| || || || || ||multiple label identifiers|| || || || || ||# label-separator[#label-separator-note label separator]|| || ||::|| || ||# namespace-decl[#namespace-decl-note namespace declaration]|| || ||namespace || || ||child namespace declaration|| || || || || ||unqualified import of namespace|| || || || || ||unqualified import of definitions|| || || || || ||# pkg-management[#pkg-management-note list installed packaged, install a package]|| || || || || ||||||||||~ # objects[#objects-note objects]|| ||~ ||~ [#javascript javascript]||~ [#smalltalk smalltalk]||~ [#tcl tcl]||~ [#autohotkey autohotkey]|| ||# def-class[#def-class-note define class] _ @< >@||function Int(i) { _ @< >@this.value = i === undefined ? 0 : i; _ }|| || || || ||# create-obj[#create-obj-note create object] _ @< >@||var i = new Int(); _ var i2 = new Int(7);|| || || || ||# instance-var[#instance-var-note instance variable visibility]||##gray|//public//##|| || || || ||# getter-setter[#getter-setter-note get and set instance variable] _ @< >@||var v = i.value; _ i.value = v + 1;|| || || || ||# def-method[#def-method-note define method] _ @< >@||##gray|@@//@@ inside constructor:## _ this.plus = function(v) { _ @< >@return this.value + v; _ }; _ _ ##gray|@@//@@ outside constructor:## _ Int.prototype.plus = function (v) { _ @< >@return this.value + v; _ }|| || || || ||# invoke-method[#invoke-method-note invoke method] _ @< >@||i.plus(3);|| || || || ||||||||||~ # inheritance-polymorphism[#inheritance-polymorphism-note inheritance and polymorphism]|| ||~ ||~ [#javascript javascript]||~ [#smalltalk smalltalk]||~ [#tcl tcl]||~ [#autohotkey autohotkey]|| ||# inheritance[#inheritance-note subclass] _ @< >@|| || || || || ||# mixin[#mixin-note mixin]|| || || || || ||# op-overload[#op-overload-note overload operator]|| || || || || ||||||||||~ # reflection[#reflection-note reflection]|| ||~ ||~ [#javascript javascript]||~ [#smalltalk smalltalk]||~ [#tcl tcl]||~ [#autohotkey autohotkey]|| ||# object-id[#object-id-note object id] _ @< >@||##gray|//none//##|| || || || ||# inspect-type[#inspect-type-note inspect type] _ @< >@||typeof([]) === ‘object’|| || || || ||# types[#types-note basic types]||number _ string _ boolean _ undefined _ function _ object _ _ ##gray|# these evaluate as ‘object’:## _ typeof(null) _ typeof([]) _ typeof({})|| || || || ||# inspect-class[#inspect-class-note inspect class]||##gray|@@//@@ returns prototype object:## _ Object.getPrototypeOf(o)||’hello’ class|| || || ||# inspect-class-hierarchy[#inspect-class-hierarchy-note inspect class hierarchy]||var pa = Object.getPrototypeOf(o) _ ##gray|@@//@@prototype’s of prototype object:## _ var grandpa = Object.getPrototypeOf(pa)|| || || || ||# has-method[#has-method-note has method?] _ @< >@||o.reverse && typeof(o.reverse) === ‘function’|| || || || ||# msg-passing[#msg-passing-note message passing] _ @< >@||##gray|//not a standard feature//##|| || || || ||# eval[#eval-note eval] _ @< >@||eval(‘1 + 1’)|| || || || ||# list-obj-methods[#list-obj-methods-note list object methods] _ @< >@|| ||1 class selectors.|| || || ||# list-obj-attr[#list-obj-attr-note list object attributes] _ @< >@|| || || || || ||# list-loaded-lib[#list-loaded-lib-note list loaded libraries]|| || || || || ||# list-loaded-namespaces[#list-loaded-namespaces-note list loaded namespaces]|| || || || || ||# inspect-namespace[#inspect-namespace-note inspect namespace]|| || || || || ||# pretty-print[#pretty-print-note pretty-print] _ @< >@||var d = {"lorem”: 1, “ipsum”: [2, 3]}; _ console.log(JSON.stringify(d, null, 2));|| || || || ||# src-line-file[#src-line-file-note source line number and file name]|| || || || || ||# cmd-line-doc[#cmd-line-doc-note command line documentation]|| || || || || ||||||||||~ # gui[#gui-note gui]|| ||~ ||~ [#javascript javascript]||~ [#smalltalk smalltalk]||~ [#tcl tcl]||~ [#autohotkey autohotkey]|| ||pop-up box||var app = Application.currentApplication() _ app.includeStandardAdditions = true _ app.displayAlert(‘hi world’)|| ||package require Tk _ _ wm title . _ grid [ttk::frame .f -padding “10 10 10 10”] _ grid [ttk::label .f.t -text “hi world”]||msgbox % “hi world”|| ||button|| || || || || ||text entry|| || || || || ||frame|| || || || || ||label|| || || || || ||image|| || || || || ||||||||||~ # net-web[#net-web-note net and web]|| ||~ ||~ [#javascript javascript]||~ [#smalltalk smalltalk]||~ [#tcl tcl]||~ [#autohotkey autohotkey]|| ||# hostname-ip[#hostname-ip-note get local hostname, dns lookup, reverse dns lookup]|| || || || || ||# http-get[#http-get-note http get] _ @< >@|| || || || || ||# http-post[#http-post-note http post] _ @< >@|| || || || || ||# serve-pwd[#serve-pwd-note serve working directory]|| || || || || ||# absolute-url[#absolute-url-note absolute url] _ ##gray|//from base and relative url//##|| || || || || ||# parse-url[#parse-url-note parse url]|| || || || || ||# url-encode[#url-encode-note url encode/decode] _ @< >@|| || || || || ||# html-escape[#html-escape-note html escape] _ ##gray|//escape character data, escape attribute value, unescape html entities//##|| || || || || ||# base64[#base64-note base64 encode/decode]|| || || || || ||~ ||~ ##EFEFEF|@@_________________________________________@@##||~ ##EFEFEF|@@______________________________________@@##||~ ##EFEFEF|@@______________________________________@@##||~ ##EFEFEF|@@_________________________________________@@##||
# general-note + [#general General]
# version-used-note ++ [#version-used version used]
The version of the language used for verifying the examples in the reference sheet.
# version-note ++ [#version show version]
How to get the version.
# grammar-invocation-note + [#grammar-invocation Grammar and Invocation]
# interpreter-note ++ [#interpreter interpreter]
The customary name of the interpreter and how to invoke it.
# cmd-line-program-note ++ [#cmd-line-program command line program]
How to pass a single command to be executed as a command line argument.
# stmt-separator-note ++ [#stmt-separator statement separator]
How the parser determines the end of a statement.
tcl:
Code fragments such as
or
result in {{invalid command name}} errors when used as statements.
The following is a valid statement:
The above cannot be used as an argument to a command without putting it inside square brackets, however.
Since the constructs which can be used as statements and the constructs which can be used in the positions where expressions are normally used are disjoint, we claim that expressions are not statements in Tcl.
# block-delimiters-note ++ [#block-delimiters block delimiters]
How blocks are delimited.
tcl:
The block delimiters {} and ““ are the same as the string delimiters. Double quotes ““ cause variable interpolation and as a result they are not often used to delimit blocks.
The following three lines of code behave the same:
code if {true} {puts “true”}
if “true” “puts "true"”
if “true” “puts {true}” /code
# expr-stmt-note ++ [#expr-stmt are expressions statements]
Whether an expression can be used where a statement is expected.
# comment-note ++ [#comment to end-of-line comment]
How to make the remainder of the line a comment.
# multiline-comment-note ++ [#multiline-comment multiline comment]
How to comment out multiple lines.
tcl:
The method described requires that there not be an unmatched right curly bracket in the comment.
# var-expr-note + [#var-expr Variables and Expressions]
# identifiers-case-sensitive-note ++ [#identifiers-case-sensitive are identifiers case sensitive]
# assignment-note ++ [#assignment assignment]
How to assign a value to a variable.
# parallel-assignment-note ++ [#parallel-assignment parallel assignment]
How to assign values to variables in parallel.
# swap-note ++ [#swap swap]
How to exchange the values held by two variables.
# compound-assignment-note ++ [#compound-assignment compound assignment]
The compound assignment operators for arithmetic, string, and bit operations
# incr-decr-note ++ [#incr-decr increment and decrement]
The C-style increment and decrement operators which can be used in expressions.
# var-decl-note ++ [#var-decl variable declaration]
How to declare a variable.
# null-note ++ [#null null]
The null literal.
tcl
Tcl has has no null value.
# null-test-note ++ [#null-test null test]
How to test if a value is null.
# undef-access-note ++ [#undef-access undefined variable]
The value of an undefined variable, or the behavior if there is no such value.
tcl:
The following test can be used to determine if a variable is defined:
code expr ![info exists v] /code
# arithmetic-logic-note + [#arithmetic-logic Arithmetic and Logic]
# true-false-note ++ [#true-false true and false]
The literals for true and false.
# falsehoods-note ++ [#falsehoods falsehoods]
Values which are false in conditional expressions.
tcl:
0 is false and all other numeric values are true. For non-numeric strings, “no” and “false” are false, and “yes” and “true” are true. The comparison is case insensitive. All other non-numeric strings raise an error when evaluated in a boolean context.
# logical-ops-note ++ [#logical-ops logical operators]
Logical and, or, and not.
# conditional-expr-note ++ [#conditional-expr conditional expression]
The syntax for a conditional expression.
# relational-expr-note ++ [#relational-expr relational expression]
tcl
To evaluate a relational expression outside of the the conditional of an {{if}} statement, the {{expr}} command can be used.
Use square brackets to make an expression an argument of a command:
# relational-operators ++ relational operators
tcl:
The {{eq}} and {{ne}} operators always perform comparisons on their operators as strings. If the arguments are numeric, they are converted to a standard floating point representation.
code % expr {"0” eq “00”} 0 % expr {"0” == “00”} 1 /code
The {{==}} and {{!=}} operators try to convert their arguments to a numeric form for the purpose of comparison. String comparison is used when no numeric conversion is possible:
code % expr {"lorem” == “ipsum”} 0 /code
The relational operators can be invoked as commands in the following manner:
code % ::tcl::mathop::== 1 1 1 % ::tcl::mathop::!= 1 1 0 % ::tcl::mathop::> 1 1 %::tcl::mathop::< 1 1 0 % ::tcl::mathop::>= 1 1 1 % ::tcl::mathop::<= 1 1 1 % ::tcl::mathop::eq “lorem” “ipsum” 0 %::tcl::mathop::ne “lorem” “ipsum” 1 /code
autohotkey:
{{<>}} is a synonym for {{!=}}.
# string-to-number ++ convert from string
# number-to-string ++ convert to string
# arithmetic-expr ++ arithmetic expressions
How to evaluate an arithmetic expression.
tcl:
Arithmetic expressions are normally evaluated with the {{expr}} command. However, the conditional argument of an {{if}} statement is always evaluated as an expression.
# arithmetic-operators ++ arithmetic operators
The operators for addition, subtraction, multiplication, float division, integer division, modulus, and exponentiation. Some languages provide a function //pow// instead of an operator for exponentiation.
tcl:
Arithmetic operators are normally used as arguments to {{expr}}, but commands also exist for each of them:
code ::tcl::mathop::+ ::tcl::mathop::- ::tcl::mathop::* ::tcl::mathop::/ ::tcl::mathop::** ::tcl::mathop::% /code
# integer-division ++ integer division
How to perform integer division.
# float-division ++ float division
How to perform floating point division, even if the operands might be integers.
# arithmetic-functions ++ arithmetic functions
Functions for computing square root, natural exponent, natural logarithm, sine, cosine, tangent, arcsine, arccosine, arctangent, and //atan2//.
The trigonometric functions are all in radians. //atan2// takes two arguments which are the x and y co-ordinates of a vector in the Cartesian plane. It returns the angle to the positive x-axis made by the vector.
# arithmetic-truncation ++ arithmetic truncation
# division-zero ++ division by zero
# integer-overflow ++ integer overflow
# float-overflow ++ float overflow
# sqrt-negative-two ++ sqrt -2
The result of taking the square root of -2.
# random ++ random integer, uniform float
The examples show how to generate a uniform random integer in the range from 0 to 99, inclusive; how to generate a uniform float in the range 0.0 to 1.0; how to generate a float from a standard normal distribution
# seed-random ++ seed random numbers
# bit-operators ++ bit operators
# strings-note + [#strings Strings]
# string-literal ++ string literal
The syntax for a string literal and how to escape the delimiter.
# string-literal-newline ++ newline in literal
Whether a newline character sequence can be included in a string.
For all the languages described in this reference sheet a string literal is permitted to encompass multiple lines in the source code and the resulting string will contain the same number of lines.
# string-escapes ++ escapes
Character escape sequences which can be used in string literals.
# variable-interpolation ++ variable interpolation
How to interpolate variables in a string.
# string-length ++ length
How to get the length of a string.
# index-substring ++ index substring
How to find the index of the start of a substring in a string.
# extract-substring ++ extract substring
# string-concatenation ++ string concatenation
The string concatenation operator.
# split ++ split
How to split a string into an array of strings.
tcl:
//split// takes an optional 2nd argument which is a string containing the characters to split on. //split// can only split on characters, not strings or regular expressions. For each pair of adjacent splitting characters in the input string, there will be an empty string in the result list.
# join ++ join
How to concatenate the elements of an array into a string with a separator.
# scan ++ scan
# sprintf ++ sprintf
How to create a string using a printf style format.
# case ++ case manipulation
# strip ++ strip
# pad ++ pad on right, pad on left
# str-to-num-note ++ [#str-to-num string to number]
tcl:
All values are strings. The //expr// function will concatenate the arguments together and then evaluate the string as a numerical expression. If all the numbers are integers, the expression is computed using integer arithmetic. Otherwise floating point arithmetic is used. The variables can contain compound arithmetic expressions; the following script outputs 10:
code set a “7+3” puts [expr $a] /code
# regex-note + [#regexes Regular Expressions]
# regex-match-note ++ [#regex-match regex match]
How to test whether a regular expression matches a string.
# regex-modifiers-note ++ [#regex-modifiers modifiers]
tcl:
||~ modifier||~ description|| ||-all||causes regexp to return number of matches in string; causes regsub to replace all occurrences of match|| ||-expanded||ignore whitespace in patten|| ||-indices||modifies group capture: returns start and end indices of the substring instead of the substring itself|| ||-inline||return the total match and each of the group captures as a list. Normally the number of matches is returned|| ||-line||same as using -lineanchor and -linestop|| ||-lineanchor||causes ^ and $ to match the beginning and ending of lines (\A and \Z still match beginning and ending of string)|| ||-linestop||causes . to not matcch a newline|| ||-nocase||makes matching case insensitive||
# single-subst-note ++ [#single-subst single substitution]
How to replace the first occurrence of a pattern in a string.
tcl:
To replace only the first occurrence of the pattern, omit the {{-all}} flag:
code set s “do re mi mi mi” regsub “mi” $s “ma” /code
# global-subst-note ++ [#global-subst global substitution]
How to replace all occurrences of a pattern in a string.
# dates-time-note + [#dates-time Dates and Time]
The Unix epoch is the number of seconds since January 1, 1970 UTC. In the case of Lua, the native date/time object is the Unix epoch, so no conversion is needed.
# arrays-note + [#arrays Arrays]
tcl:
Tcl arrays are associative arrays. The dict type is new in Tcl 8.5. See the documentation for [http://www.tcl.tk/man/tcl8.5/TclCmd/array.htm array] and [http://www.tcl.tk/man/tcl8.5/TclCmd/dict.htm dict].
# array-literal ++ array literal
Array literal syntax.
# array-size ++ array size
How to get the number of elements in an array.
# array-lookup ++ array lookup
How to access a value in an array by index.
tcl:
Does not support negative indices. To change the 2nd element in the list //a// to 8, use
//lset// will not increase the size of the list if the index is out of bounds. For more list manipulation commands see http://www.tcl.tk/man/tcl/tutorial/Tcl15.html.
# array-slice ++ array slice
How to slice a subarray from an array.
# array-iteration ++ array iteration
# membership ++ membership
How to test for membership in an array.
# intersection ++ intersection
How to compute an intersection.
# union ++ union
# map ++ map
# filter ++ filter
# reduce ++ reduce
# universal-predicate ++ universal predicate
How to test whether a condition holds for all members of an array. Always true for an empty array.
# existential-predicate ++ existential predicate
How to test whether an item in an array exists for which a condition holds. Always false for an empty array.
# dictionaries-note + [#dictionaries Dictionaries]
tcl:
The {{dict}} type was introduced in Tcl 8.5.
In earlier versions of Tcl associative arrays were used when a dictionary type was needed, and they remain an alternative in Tcl 8.5. Associative arrays are stored in variables as strings. The {{array}} command is used to treat the string as an associative array:
code array set d [list “t” 1 “f” 0] array size d $d(t) array set d [list “t” 2] info exists d(t) array unset d “t” foreach {k v} [array get d] { puts k puts v } /code
# dictionary-literal ++ dictionary literal
# dictionary-size ++ dictionary size
# dictionary-lookup ++ dictionary lookup
# dictionary-iteration ++ dictionary iteration
# out-of-bounds ++ out of bounds behavior
# functions-note + [#functions Functions]
tcl:
Tcl variables inside functions have local scope.
# function-definition ++ function definition
# function-invocation ++ function invocation
# missing-argument ++ missing argument value
Value of an argument variable if a function is invoked with fewer arguments than are declared.
# extra-arguments ++ extra arguments
If a function is invoked with more arguments than are declared, how the function can access them.
# default-argument ++ default argument value
How to declare a default value for an argument.
# variable-arguments ++ variable number of arguments
How to write a function which accepts a variable number of argument.
# named-parameters ++ named parameters
How to write a function which uses named parameters.
# return-value ++ return value
# lambda-declaration ++ lambda declaration
How to define a lambda function.
# lambda-invocation ++ lambda invocation
# default-scope ++ default scope
# execution-control-note + [#execution-control Execution Control]
# if ++ if
tcl:
Tcl also has a switch:
code switch $a 0 { puts “no” } 1 { puts “yes” } 2 { puts “maybe” } default { puts “error” } /code
autohotkey:
The traditional style omits the parens around the conditionals.
code |if n = 0 { msgbox % “zero hits” } _ else if n = 1 { msgbox % “one hit” } else { msgbox % n . “ hits” } /code
# while ++ while
# break-continue ++ break/continue/redo
//break// exits a //for// or //while// loop immediately. //continue// goes to the next iteration of the loop. //redo// goes back to the beginning of the current iteration.
# for ++ for
# exceptions-note + [#exceptions Exceptions]
# raise-exception ++ raise exception
How to raise an exception.
# catch-exception ++ catch exception
How to handle an exception.
# uncaught-exception ++ uncaught exception behavior
System behavior if an exception goes uncaught. Most interpreters print the exception message to stderr and exit with a nonzero status.
tcl:
A tcl process can have multiple interpreters and multiple threads. However, each interpreter is limited to a single thread.
# wait-on-thread ++ wait on thread
# file-note + [#files Files]
# print-to-stdout ++ print to standard out
tcl:
To prevent //puts// from appending a newline to the output, use
code puts -nonewline “hello” /code
# standard-filehandles ++ standard filehandles
# read-line ++ read line
# read-file ++ read file
# write-file ++ write to file
# append-file ++ append to file
# gui-note + [#gui GUI]
# file-fmt-note + [#file-fmt File Formats]
# directories-note + [#directories Directories]
# processes-environment-note + [#processes-environment Processes and Environment]
# external-command ++ external command
tcl
When using tclsh as a shell or repl, external commands that do not have the same name as a built-in or user defined function can be executed directly without using the exec command.
# backticks ++ backticks
# command-line-args ++ command line args
# speech ++ speech
How to make the computer talk.
# environment-variable ++ environment variable
# command-path ++ command path
The directory containing a command. Also indicates if the command is a built-in, alias, or function. Shows the definition of aliases and functions.
# exit ++ exit
# set-signal-handler ++ set signal handler
# libraries-namespaces-note + [#libraries-namespaces Libraries and Namespaces]
# library ++ library
What a library looks like.
# import-library ++ import library
# library-path ++ library path
# namespace-declaration ++ namespace declaration
# namespace-separator ++ namespace separator
# reflection-note + [#reflection Reflection]
# class ++ class
# smalltalk + [#top Smalltalk]
[#image-vm image and virtual machine] | [#browser-workspace-transcript browser, workspace, and transcript] | [#the-smalltalk-lang the smalltalk language]
# image-vm ++ image and virtual machine
Executable Smalltalk consists of an //image// and a //virtual machine//. A Smalltalk image is equivalent to a program, except that it also contains the state of a Smalltalk process; a Smalltalk process can save itself as an image at any point in its execution. The Smalltalk image is usually portable, whereas the virtual machine is operating system specific.
To create a new Smalltalk executable, one copies an existing image, launches it, adds to or modifies the code while the process is running, and then persists the new code and the process state when the executable is done.
After a fresh installation of Pharo 3.0 on Mac OS X, one has a image named {{Pharo.image}} and a virtual machine named {{Pharo}}. One can launch the program at the command line by passing the image to the virtual machine as an argument:
code $ ls -l Pharo.image -rw-rw-r– 1 hpglot staff 21802780 Dec 12 06:38 Pharo.image
$ ls -l pharo-vm/Pharo.app/Contents/MacOS/Pharo -rwxr-xr-x 1 hpglot staff 867488 May 15 2014 pharo-vm/Pharo.app/Contents/MacOS/Pharo
$ ./pharo-vm/Pharo.app/Contents/MacOS/Pharo Pharo.image /code
It is worth noting that even after a fresh installation, the image is already much larger than the virtual machine. The standard library and any ofther classes distributed with the implementation are implemented in Smalltalk; they are in the image, not the virtual matchine.
# browser-workspace-transcript ++ browser, workspace, and transcript
# the-smalltalk-lang ++ the smalltalk language
All values which can be stored in variables are objects.
Every expression and statement is implemented as a message which is sent to an object.
Messages are classified as //unary//, //binary//, or //keyword//.
Examples of unary messages:
code 1 class. false not. Date today. /code
Examples of binary messages:
code 2 * 7. true & true. 3 < 10. ‘Hello, ‘, ‘World!’. /code
Examples of keyword messages:
Precedence of messages.
Cascaded messages.
No functions, just methods and blocks.
# tcl + [#top Tcl]
[http://tmml.sourceforge.net/doc/tcl/ Tcl Reference Manual] [http://tcllib.sourceforge.net/doc/ Tcl Standard Library]
Tcl has some traits which will be familiar to anyone who has done Unix shell script programming:
(1) variables have a $ prefix except when values are assigned to them, in which case they are used unadorned:
(2) statements consist of a command and zero or more arguments. Commands which are not built-in functions or user defined functions are resolved by looking for an external command in the search path and running it.
(3) the values are always stored in variables as strings. Commands which expect numeric arguments perform an implicit conversion, so there isn’t much practical consequence for the developer.
(4) in the absence of quoting (““, {}, []) the arguments of a command are parsed into words using whitespace; commas are not used to separate arguments.
(5) square brackets [] must be used to execute a function and use its return value as an argument. A combination of square brackets [] and the {{expr}} command must be used to evaluate an expression and use its value as an argument:
code puts [format “%10s” “lorem”] puts [expr 1 + 1] /code
Square brackets can be used to invoke an external command, but the value of the square brackets containing an external command is always the empty string: ““.
Unlike shells, *, ?, ~ in variable names are not automatically expanded using the filesystem, but this behavior can be invoked with the glob command.
# autohotkey + [#top AutoHotkey]
[http://www.autohotkey.com/docs/ Documentation]
# javascript + [#top JavaScript]
[https://developer.mozilla.org/en-US/docs/Web/JavaScript Mozilla Developer Network: JavaScript] [https://developer.apple.com/library/mac/releasenotes/InterapplicationCommunication/RN-JavaScriptForAutomation/ JavaScript for Automation: Release Notes] [https://developer.mozilla.org/en-US/docs/Web/API/document Mozilla Developer Network: Document] [https://developer.mozilla.org/en-US/docs/Web/API/Window Mozilla Document Network: Window] [http://www.w3.org/TR/DOM-Level-3-Core/ W3C: Document Object Model (DOM) Level 3 Core Specification] [http://www.w3.org/TR/DOM-Level-3-Events/ W3C: Document Object Model (DOM) Level 3 Events Specification]
Most browsers include a debugger which can be launched with a keystroke:
||~ browser||~ mac||~ windows||~ linux|| ||Chrome||⌥⌘J||Cmd+Shift+J||Cmd+Shift+J|| ||Firefox||⌥⌘S||Cmd+Shift+S||Cmd+Shift+S|| ||Safari||⌥⌘C|| || ||
The debugger has a console pane, which is a JavaScript REPL.
Math.log(10) 2.302585092994046
alert(“Hello, World!”) /code
The console provides a global object named {{document}} which provides access to the DOM of the current page:
document.getElementsByTagName(“div”).length 302 /code
//TODO: more ways to select node elements. Attributes of node elements.//
There is also a global object named {{window}} which is useful.
JavaScript can be embedded in an HTML document using the {{}} tag:
code var sum = 1 + 2; alert(‘the sum is ‘ + sum); /code
Alternatively the JavaScript can be in a separate file served by the same server:
{{}} tags can be placed in either the {{}} or the {{}} of an {{}} document. They are executed as they are encountered by the browser. If there is a syntax error, then none of the JavaScript in the {{}} tag is executed. If there is an unhandled exception, the browser stops execution of the {{}} at that point. Neither syntax errors nor unhandled exceptions prevent the browser from executing JavaScript in subsequent {{}} tags.
//using JavaScript to modify the DOM//
//waiting for all JavaScript to load//
//javascript URL//
//DOM events//
To guard against websites serving malicious JavaScript code, the JavaScript interpreters in browsers do not provide the ability to interact with the local operating system. In particular, client-side JavaScript cannot read or write to files. Client-side JavaScript cannot spawn other processes.
Client-side JavaScript can make HTTP requests. Client-side JavaScript can modify the DOM of an HTML page which was served from the same [https://developer.mozilla.org/en-US/docs/Web/JavaScript/Same_origin_policy_for_JavaScript origin] as the JavaScript. To be from the same origin, the URLs must have the same protocol, domain, and port. Client-side JavaScript can also get and set cookies which share the same origin. The origin policy for cookies is slightly relaxed, since the JavaScript can also get and set cookies for a parent domain, excluding public top level domains such as {{.com}}, {{.net}}, and {{.org}}.