Skip to content

Commit c0c9e27

Browse files
committed
array programming and function pointers
1 parent 8df8534 commit c0c9e27

1 file changed

Lines changed: 41 additions & 1 deletion

File tree

content/posts/odin-guide.md

Lines changed: 41 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -438,8 +438,48 @@ value := enum_array[.First]
438438

439439
## Array Programming (Operator Overloading)
440440

441+
Odin doesnt have traditional operator overloading, because operator overloading can cause a lot of hidden behaviour.
442+
But for a lot of linear algebra, you still need to be able to do operations on complex types, like vectors and matrices.
443+
This can be done with array programming.
444+
445+
Arrays can represent complex structures, and in odin arrays can be used with operators:
446+
447+
```odin
448+
Vector3 :: [3]f32
449+
a := Vector3{1, 2, 3}
450+
b := Vector3{1, 2, 3}
451+
c := a + b // {2, 4, 6}
452+
d := a * b // {1, 4, 9}
453+
```
454+
455+
Build in fields like `xyzw` and `rgba` are available on any array with a length lower than 4 elements:
456+
457+
```odin
458+
Vector3 :: [3]f32
459+
foo :: proc(a: Vector3) -> f32 {
460+
return a.x + a.y + a.z // notice xyz is buildin
461+
}
462+
```
463+
441464
## Polymorphism (Generics)
442465

443466
## Strings
444467

445-
## Function Pointers / Function Types
468+
## Function Pointers / Function Types
469+
470+
A procedure type is internally a pointer to a procedure in memory. nil is the zero value a procedure type.
471+
Procedures are first class types, and can be passed as an argument to another procedure.
472+
473+
```odin
474+
// custom function pointer type
475+
Callback :: proc(int, int) -> int // create custom type
476+
Callback :: proc(x: int, y: int) -> int // names are optional
477+
478+
// usage of custom procedure type
479+
foo: Callback // declare a as callback procedure type
480+
foo = proc(x: int, y: int) -> int { return x + y } // assign behaviour to procedure variable
481+
482+
// custom procedure type as argument
483+
bar :: proc(cb: Callback) { ... }
484+
bar :: proc(cb: proc(int, int) -> int) { ... } // this is equivelant
485+
```

0 commit comments

Comments
 (0)