Copper Cheat Sheet
Cheat sheet to understand most Copper code I've published without knowing Copper.
Identifier
(starting with an uppercase) - a type or moduleself
- the implicit first parameter in methods (def
)def
- define an instance functiondo
- see macros below$A
- The ascii character value ($A
is same as65
)!
- an array or struct on stack or directly embedded (instead of a pointer to it)~
- the distance operator (ptr - size -> ptr, ptr ~ ptr -> size)*
- in place of the type of a parameter : it can be of any type, including a type*
- after def or func : the type of self can be a subtype corresponding the the one of the receiver?
- An optional type: the value can take a reservednil
value that represents no value..expr
- equivalent toT.expr
whereT
is the expected type of the expressionyield(args)
- invoke a block passed to the macro
Refs
ref name
- a reference to a functionref [T] name
- a reference to a function in class or moduleT
ref (T) name
- a reference to a method or attributeref (expr) name
- a pointer to the attribute of the objectexpr
Macros
Defining a macro : like a function or method, but with do
:
// A macro that takes
// a parameter 'n',
// a block parameter that takes an Int and must return an Int
// and returns and Int
func sum(n: Int) do (Int)[Int]: Int
var sum = Int: 0
var i = Int: 1
while i <= n
sum += yield(i)
i += 1
end
return sum
end
Invoking the macro:
// Will get the sum 2 + 4 + 6 + ... + 20
var result =
sum(10) do x
...
// 'pass' returns a value to the 'yield' that has invoked this block
pass x * 2
end