### Basic raylib Window Initialization and Input Handling Source: https://github.com/odin-lang/odin-lang.org/blob/master/content/news/2024-04.md This snippet demonstrates the fundamental setup for a raylib application, including window creation and capturing input events. It serves as a starting point for simple GUI applications or games. ```odin raylib.InitWindow(width, height, "Window Title") // Grab input events // Do some stuff // Draw something ``` -------------------------------- ### Condition-Response System Example Source: https://github.com/odin-lang/odin-lang.org/blob/master/content/news/2024-05.md This example demonstrates a simple condition-response system implemented in Odin. It reads conditions and responses from a text file to drive game logic. ```odin package main import "core:fmt" import "core:strings" import "core:os" Condition :: struct { text: string, response: string, } main :: proc () { conditions := []Condition{ Condition{"is_raining", "take_umbrella"}, Condition{"is_sunny", "wear_sunglasses"}, Condition{"is_windy", "wear_jacket"}, } current_condition := "is_raining" response := "do_nothing" for c in conditions { if c.text == current_condition { response = c.response break } } fmt.println("Current condition:", current_condition) fmt.println("Response:", response) } ``` -------------------------------- ### Example Usage of ufbx Bindings Source: https://github.com/odin-lang/odin-lang.org/blob/master/content/news/2023-08.md A basic example demonstrating the usage of the ufbx bindings for Odin, likely for loading and processing FBX files. ```odin package main import ( // "core:fmt" // "core:mem" // "core:runtime" // "core:strings" // "core:time" "ufbx" ) main :: proc () { // TODO: Add example code here } ``` -------------------------------- ### Minimal Metal Window Example Source: https://github.com/odin-lang/odin-lang.org/blob/master/content/news/2023-08.md A minimal example for creating a Metal window using Odin, likely for graphics applications on Apple platforms. ```odin package main import ( "core:runtime" "metal_window" ) main :: proc () { metal_window.init (nil) runtime.main_loop () } ``` -------------------------------- ### Install Bootstrap CSS with NuGet Source: https://github.com/odin-lang/odin-lang.org/blob/master/themes/odin/assets/node_modules/bootstrap/README.md Install the Bootstrap CSS package using NuGet Package Manager Console. ```powershell Install-Package bootstrap ``` -------------------------------- ### Install Bootstrap with Composer Source: https://github.com/odin-lang/odin-lang.org/blob/master/themes/odin/assets/node_modules/bootstrap/README.md Install Bootstrap using Composer, a dependency manager for PHP. Specify the version for precise control. ```bash composer require twbs/bootstrap:5.1.0 ``` -------------------------------- ### Install Bootstrap with npm Source: https://github.com/odin-lang/odin-lang.org/blob/master/themes/odin/assets/node_modules/bootstrap/README.md Use npm to install Bootstrap for your project. This is a common method for managing front-end dependencies. ```bash npm install bootstrap ``` -------------------------------- ### Simple Command-Line Argument Parsing Source: https://github.com/odin-lang/odin-lang.org/blob/master/content/news/2023-08.md An example of using the ClOdin package for simple command-line argument parsing in Odin. ```odin package main import ( "core:fmt" "ClOdin" ) main :: proc () { ClOdin.parse () // TODO: Add example arguments fmt.println ("Hello World!") } ``` -------------------------------- ### Thread Creation and Management Source: https://github.com/odin-lang/odin-lang.org/blob/master/content/docs/demo.md Demonstrates creating, starting, managing, and destroying threads. It includes a loop to check thread completion and remove finished threads. ```odin threads := make([dynamic]^thread.Thread, 0, len(prefix_table)) defer delete(threads) for _ in prefix_table { if t := thread.create(worker_proc); t != nil { t.init_context = context t.user_index = len(threads) append(&threads, t) thread.start(t) } } for len(threads) > 0 { for i := 0; i < len(threads); /**/ { if t := threads[i]; thread.is_done(t) { fmt.printf("Thread %d is done\n", t.user_index) thread.destroy(t) ordered_remove(&threads, i) } else { i += 1 } } } ``` -------------------------------- ### Install WASM Linker (MacOS) Source: https://github.com/odin-lang/odin-lang.org/blob/master/content/docs/install.md Install the 'lld' formula using Homebrew, which provides the 'wasm-ld' linker required for compiling Odin to WASM. ```bash brew install lld ``` -------------------------------- ### Install Bootstrap with yarn Source: https://github.com/odin-lang/odin-lang.org/blob/master/themes/odin/assets/node_modules/bootstrap/README.md Use yarn to install Bootstrap for your project. Yarn is another popular package manager for JavaScript. ```bash yarn add bootstrap ``` -------------------------------- ### Setup Tracking Allocator in Odin Source: https://github.com/odin-lang/odin-lang.org/blob/master/content/docs/overview.md Enables memory leak detection and bad free warnings during debug builds. This setup should be placed at the beginning of the main procedure. ```odin package main import "core:fmt" import "core:mem" main :: proc() { when ODIN_DEBUG { track: mem.Tracking_Allocator mem.tracking_allocator_init(&track, context.allocator) context.allocator = mem.tracking_allocator(&track) defer { if len(track.allocation_map) > 0 { fmt.eprintf("=== %v allocations not freed: ===\n", len(track.allocation_map)) for _, entry in track.allocation_map { fmt.eprintf("- %v bytes @ %v\n", entry.size, entry.location) } } mem.tracking_allocator_destroy(&track) } } do_stuff() } ``` -------------------------------- ### Bit Set Initialization and Usage Source: https://github.com/odin-lang/odin-lang.org/blob/master/content/docs/overview.md Illustrates initializing and using bit sets with elements from their defined types. The `card` procedure can be used to get the number of set elements. ```odin x: Char_Set x = {'A', 'B', 'Y'} y: Direction_Set y = {.North, .West} ``` ```odin x: Direction_Set x = {.North, .West} count := card(x) assert(count == 2) ``` -------------------------------- ### Odin Main Procedure Source: https://github.com/odin-lang/odin-lang.org/blob/master/content/docs/demo.md The entry point for an Odin program, demonstrating the use of `when true` for conditional compilation and calling various example procedures. ```odin main :: proc() { /* For More Odin Examples - https://github.com/odin-lang/examples This repository contains examples of how certain things can be accomplished in idiomatic Odin, allowing you learn its semantics, as well as how to use parts of the core and vendor package collections. */ when true { the_basics() control_flow() named_proc_return_parameters() variadic_procedures() explicit_procedure_overloading() struct_type() union_type() using_statement() implicit_context_system() parametric_polymorphism() threading_example() array_programming() map_type() implicit_selector_expression() partial_switch() cstring_example() bit_set_type() deferred_procedure_associations() reflection() quaternions() unroll_for_statement() where_clauses() foreign_system() ranged_fields_for_array_compound_literals() deprecated_attribute() range_statements_with_multiple_return_values() soa_struct_layout() constant_literal_expressions() union_maybe() explicit_context_definition() or_else_operator() or_return_operator() or_break_and_or_continue_operators() arbitrary_precision_mathematics() matrix_type() bit_field_type() } } ``` -------------------------------- ### Basic Threading Example in Odin Source: https://github.com/odin-lang/odin-lang.org/blob/master/content/docs/demo.md Demonstrates basic thread creation and management in Odin. It shows how to define a worker procedure that runs in a separate thread and accesses shared data like an array of strings. ```odin prefix_table := [?]string{ "White", "Red", "Green", "Blue", "Octarine", "Black", } print_mutex := b64(false) @(disabled=!thread.IS_SUPPORTED) threading_example :: proc() { fmt.println("\n# threading_example") did_acquire :: proc(m: ^b64) -> (acquired: bool) { res, ok := intrinsics.atomic_compare_exchange_strong(m, false, true) return ok && res == false } { // Basic Threads fmt.println("\n## Basic Threads") worker_proc :: proc(t: ^thread.Thread) { for iteration in 1..=5 { fmt.printf("Thread %d is on iteration %d\n", t.user_index, iteration) fmt.printf("`%s`: iteration %d\n", prefix_table[t.user_index], iteration) time.sleep(1 * time.Millisecond) } } ``` -------------------------------- ### Build Odin Release (Windows) Source: https://github.com/odin-lang/odin-lang.org/blob/master/content/docs/install.md Build the Odin compiler in release mode using the provided batch script. Ensure MSVC and Windows SDK are installed and the command prompt is set up. ```batch build.bat release ``` -------------------------------- ### Struct Definition Example Source: https://github.com/odin-lang/odin-lang.org/blob/master/content/docs/overview.md Defines simple structs `Vector3` and `Entity` for demonstrating `using` statement capabilities. ```odin Vector3 :: struct{x, y, z: f32} Entity :: struct { position: Vector3, orientation: quaternion128, } ``` -------------------------------- ### Array Programming Example Source: https://github.com/odin-lang/odin-lang.org/blob/master/content/docs/faq.md Demonstrates basic array operations like multiplication and swizzling. This syntax leverages Odin's array programming capabilities for concise vector operations. ```odin a, b: [4]f32; c := a * b; i := a.x * b.y; v := swizzle(a, 1, 2, 0) ``` -------------------------------- ### Using `any` for Open Type Handling Source: https://github.com/odin-lang/odin-lang.org/blob/master/content/docs/demo.md Demonstrates the use of the `any` type, which is similar to unions but allows any type. It shows type assertion and `switch` statement usage, mirroring the union example. ```odin val: any val = 137 if i, ok := val.(int); ok { fmt.println(i) } val = true fmt.println(val) val = nil switch v in val { case int: fmt.println("int", v) case bool: fmt.println("bool", v) case: fmt.println("nil") } ``` -------------------------------- ### Odin String and Cstring Conversion Examples Source: https://github.com/odin-lang/odin-lang.org/blob/master/content/docs/overview.md Illustrates the conversion between Odin's `string` and `cstring` types, highlighting the performance implications (O(n) vs O(1)) for length checks and the need for allocations when converting `string` to `cstring`. ```odin str: string = "Hellope" cstr: cstring = "Hellope" // constant literal cstr2 := string(cstr) // O(n) conversion as it requires search from the zero-terminator nstr := len(str) // O(1) ncstr := len(cstr) // O(n) ``` -------------------------------- ### Odin Tail Call Optimization Example Source: https://github.com/odin-lang/odin-lang.org/blob/master/content/news/2026-Q1.md Demonstrates tail call optimization using the #must_tail directive and specific calling conventions. This advanced feature is for users who understand its implications, especially regarding address sanitization tooling. ```odin Op_Code :: enum i32 { PUSH, ADD, SUB, MUL, DIV, HLT, } Instr :: struct { opc: Op_Code, imm: i32, } VM :: struct { stack: [10]i32, sp: int, } push :: proc "contextless" (vm: ^VM, v: i32) { vm.stack[vm.sp] = v vm.sp += 1 } pop :: proc "preserve/none" (vm: ^VM) -> i32 { vm.sp -= 1 return vm.stack[vm.sp] } // The tail-calling threaded interpreter approach exec :: proc "preserve/none" (vm: ^VM, instrs: [^]Instr) -> i32 { do_push :: proc "preserve/none" (vm: ^VM, instrs: [^]Instr) -> i32 { push(vm, instrs[0].imm) return #must_tail exec(vm, instrs[1:]) } do_add :: proc "preserve/none" (vm: ^VM, instrs: [^]Instr) -> i32 { push(vm, pop(vm) + pop(vm)) return #must_tail exec(vm, instrs[1:]) } do_sub :: proc "preserve/none" (vm: ^VM, instrs: [^]Instr) -> i32 { push(vm, pop(vm) - pop(vm)) return #must_tail exec(vm, instrs[1:]) } do_mul :: proc "preserve/none" (vm: ^VM, instrs: [^]Instr) -> i32 { push(vm, pop(vm) * pop(vm)) return #must_tail exec(vm, instrs[1:]) } do_div :: proc "preserve/none" (vm: ^VM, instrs: [^]Instr) -> i32 { push(vm, pop(vm) / pop(vm)) return #must_tail exec(vm, instrs[1:]) } do_hlt :: proc "preserve/none" (vm: ^VM, instrs: [^]Instr) -> i32 { return pop(vm) } @(static, rodata) LUT := [Op_Code](proc "preserve/none" (^VM, [^]Instr) -> i32) { .PUSH = do_push, .ADD = do_ADD, .SUB = do_SUB, .MUL = do_MUL, .DIV = do_DIV, .HLT = do_HLT, } return #must_tail LUT[instrs[0].opc](vm, instrs) } ``` -------------------------------- ### Using the len Procedure Source: https://github.com/odin-lang/odin-lang.org/blob/master/content/docs/overview.md Demonstrates how to get the length of a string using the built-in `len` procedure. If the string is a compile-time constant, the result is also a compile-time constant. ```odin len("Foo") len(some_string) ``` -------------------------------- ### Static and Dynamic Handle Map Usage Source: https://github.com/odin-lang/odin-lang.org/blob/master/content/news/2026-Q1.md Demonstrates the usage of both static and dynamic handle maps for managing entities with handles. Includes adding, getting, modifying, and removing entities, as well as iterating over the map. ```odin import hm "core:container/handle_map" Handle :: hm.Handle32 Entity :: struct { handle: Handle, pos: [2]f32, } { entities: hm.Static_Handle_Map(1024, Entity, Handle) h1 := hm.add(&entities, Entity{pos = {1, 4}}) h2 := hm.add(&entities, Entity{pos = {9, 16}}) if e, ok := hm.get(&entities, h2); ok { e.pos.x += 32 } hm.remove(&entities, h1) h3 := hm.add(&entities, Entity{pos = {6, 7}}) it := hm.iterator_make(&entities) for e, h in hm.iterate(&it) { e.pos += {1, 2} } } ``` ```odin { entities: hm.Dynamic_Handle_Map(Entity, Handle) hm.dynamic_init(&entities, context.allocator) defer hm.dynamic_destroy(&entities) h1 := hm.add(&entities, Entity{pos = {1, 4}}) h2 := hm.add(&entities, Entity{pos = {9, 16}}) if e, ok := hm.get(&entities, h2); ok { e.pos.x += 32 } hm.remove(&entities, h1) h3 := hm.add(&entities, Entity{pos = {6, 7}}) it := hm.iterator_make(&entities) for e, h in hm.iterate(&it) { e.pos += {1, 2} } } ``` -------------------------------- ### Basic Odin Main Procedure for Orca Source: https://github.com/odin-lang/odin-lang.org/blob/master/content/news/orca-support.md A minimal Odin program structure for an Orca application. The `main` procedure is the entry point, and it's currently empty, suitable for a basic window setup. ```odin package src main :: proc() {} ``` -------------------------------- ### Importing Multiple Packages for Testing Source: https://github.com/odin-lang/odin-lang.org/blob/master/content/docs/testing.md To run tests in subdirectories, declare imports for each package in a `tests.odin` file at the root of the tests directory. This setup is used in conjunction with the `-all-packages` command-line option. ```odin package tests @require import "foo" @require import "bar" @require import "gadgets" @require import "widgets" ``` -------------------------------- ### Add Odin to Bash PATH Source: https://github.com/odin-lang/odin-lang.org/blob/master/content/docs/install.md To make the Odin compiler easily accessible from any directory, add the Odin installation folder to your shell's PATH environment variable. This example is for bash. ```bash echo 'export PATH="/path/to/Odin/folder:$PATH"' >> ~/.bashrc ``` -------------------------------- ### Basic Odin Program Structure and Arguments Source: https://github.com/odin-lang/odin-lang.org/blob/master/content/docs/demo.md Demonstrates how to access command-line arguments using `os.args`. The `os.args` slice contains the executable path and any provided arguments. ```odin #+vet !using-stmt !using-param #+feature dynamic-literals package main import "core:fmt" import "core:mem" import "core:os" import "core:thread" import "core:time" import "core:reflect" import "base:runtime" import "base:intrinsics" import "core:math/big" /* Odin is a general-purpose programming language with distinct typing built for high performance, modern systems and data-oriented programming. Odin is the C alternative for the Joy of Programming. # Installing Odin Getting Started - https://odin-lang.org/docs/install/ Instructions for downloading and install the Odin compiler and libraries. # Learning Odin Getting Started - https://odin-lang.org/docs/install/ Getting Started with Odin. Downloading, installing, and getting your first program to compile and run. Overview of Odin - https://odin-lang.org/docs/overview/ An overview of the Odin programming language and its features. Frequently Asked Questions (FAQ) - https://odin-lang.org/docs/faq/ Answers to common questions about Odin. Packages - https://pkg.odin-lang.org/ Documentation for all the official packages part of the core and vendor library collections. Nightly Builds - https://odin-lang.org/docs/nightly/ Get the latest nightly builds of Odin. More Odin Examples - https://github.com/odin-lang/examples This repository contains examples of how certain things can be accomplished in idiomatic Odin, allowing you learn its semantics, as well as how to use parts of the core and vendor package collections. */ the_basics :: proc() { fmt.println("\n# the basics") { // os.args holds the path to the current executable and any arguments passed to it. if len(os.args) == 1 { fmt.printf("Hellope from %v.\n", os.args[0]) } else if len(os.args) > 2 { fmt.printf("%v, %v! from %v.\n", os.args[1], os.args[2], os.args[0]) } // Lexical elements and literals // A comment my_integer_variable: int // A comment for documentaton // Multi-line comments begin with /* and end with */. Multi-line comments can // also be nested (unlike in C): /* You can have any text or code here and have it be commented. /* NOTE: comments can be nested! */ */ // String literals are enclosed in double quotes and character literals in single quotes. // Special characters are escaped with a backslash \ some_string := "This is a string" _ = 'A' // unicode codepoint literal _ = '\n' _ = "C:\\Windows\\notepad.exe" // Raw string literals are enclosed with single back ticks _ = `C:\Windows\notepad.exe` // The length of a string in bytes can be found using the built-in `len` procedure: _ = len("Foo") _ = len(some_string) // Numbers // Numerical literals are written similar to most other programming languages. // A useful feature in Odin is that underscores are allowed for better // readability: 1_000_000_000 (one billion). A number that contains a dot is a // floating point literal: 1.0e9 (one billion). If a number literal is suffixed // with i, is an imaginary number literal: 2i (2 multiply the square root of -1). // Binary literals are prefixed with 0b, octal literals with 0o, and hexadecimal // literals 0x. A leading zero does not produce an octal constant (unlike C). // In Odin, if a numeric constant can be represented by a type without // precision loss, it will automatically convert to that type. x: int = 1.0 // A float literal but it can be represented by an integer without precision loss // Constant literals are “untyped” which means that they can implicitly convert to a type. y: int // `y` is typed of type `int` y = 1 // `1` is an untyped integer literal which can implicitly convert to `int` z: f64 // `z` is typed of type `f64` (64-bit floating point number) z = 1 // `1` is an untyped integer literal which can be implicitly converted to `f64` // No need for any suffixes or decimal places like in other languages // (with the exception of negative zero, which must be given as `-0.0`) // CONSTANTS JUST WORK!!! // Assignment statements h: int = 123 // declares a new variable `h` with type `int` and assigns a value to it h = 637 // assigns a new value to `h` // `=` is the assignment operator // You can assign multiple variables with it: a, b := 1, "hello" // declares `a` and `b` and infers the types from the assignments b, a = "byte", 0 // Note: `:=` is two tokens, `:` and `=`. The following are equivalent, /* i: int = 123 i: = 123 i := 123 */ ``` -------------------------------- ### Basic Odin Program Source: https://github.com/odin-lang/odin-lang.org/blob/master/content/docs/overview.md A simple 'Hellope!' program demonstrating package structure, imports, and the main procedure. Save this to a .odin file and compile using 'odin run'. ```odin package main import "core:fmt" main :: proc() { fmt.println("Hellope!") } ``` -------------------------------- ### Odin Map Initialization and Basic Operations Source: https://github.com/odin-lang/odin-lang.org/blob/master/content/docs/overview.md Illustrates creating a map, deferring its deletion, inserting and retrieving elements, and printing a value. ```odin m := make(map[string]int) defer delete(m) m["Bob"] = 2 fmt.println(m["Bob"]) ``` -------------------------------- ### Using Vendor GLFW Library Source: https://github.com/odin-lang/odin-lang.org/blob/master/content/docs/overview.md This snippet demonstrates how to initialize and use the GLFW library from within an Odin project. It includes setting up error and key callbacks, creating a window, and a basic event loop. ```odin package main import "base:runtime" import "core:fmt" import "vendor:glfw" error_callback :: proc "c" (code: i32, desc: cstring) { context = runtime.default_context() fmt.println(desc, code) } key_callback :: proc "c" (window: glfw.WindowHandle, key, scancode, action, mods: i32) { if key == glfw.KEY_ESCAPE && action == glfw.PRESS { glfw.SetWindowShouldClose(window, glfw.TRUE) } } main :: proc() { glfw.SetErrorCallback(error_callback) if !glfw.Init() { panic("EXIT_FAILURE") } defer glfw.Terminate() glfw.WindowHint(glfw.CONTEXT_VERSION_MAJOR, 2) glfw.WindowHint(glfw.CONTEXT_VERSION_MINOR, 0) window := glfw.CreateWindow(640, 480, "Simple example", nil, nil) if window == nil { panic("EXIT_FAILURE") } deffer glfw.DestroyWindow(window) glfw.SetKeyCallback(window, key_callback) glfw.MakeContextCurrent(window) // ... glfw.SwapInterval(1) // ... for !glfw.WindowShouldClose(window) { // ... glfw.SwapBuffers(window) glfw.PollEvents() } } ``` -------------------------------- ### Install LLVM for MacOS Source: https://github.com/odin-lang/odin-lang.org/blob/master/content/docs/install.md Install LLVM using Homebrew, which is required for building Odin on macOS. Supported versions are 17 through 22. ```bash brew install llvm ``` -------------------------------- ### Basic Job Dispatch and Wait in Odin Source: https://github.com/odin-lang/odin-lang.org/blob/master/content/news/2023-11.md Illustrates the fundamental usage of the Odin job scheduler. It shows how to initialize the scheduler, dispatch a simple job, and wait for its completion before shutting down. ```odin main :: proc() { jobs.initialize() g: jobs.Group jobs.dispatch(.Medium, jobs.make_job(&g, hello_job)) jobs.wait(&g) jobs.shutdown() } hello_job :: proc(_: rawptr) { fmt.println("Hello from thread", jobs.current_thread_index()) } ``` -------------------------------- ### Install Bootstrap Sass with NuGet Source: https://github.com/odin-lang/odin-lang.org/blob/master/themes/odin/assets/node_modules/bootstrap/README.md Install the Bootstrap Sass package using NuGet Package Manager Console for Sass compilation. ```powershell Install-Package bootstrap.sass ``` -------------------------------- ### Initialize and Use Journey ECS World Source: https://github.com/odin-lang/odin-lang.org/blob/master/content/news/2023-11.md Demonstrates initializing an ECS world, registering components, creating entities, and adding components using the Journey ECS library. It also shows how to query entities with specific components and iterate over them. ```odin package main import ecs "foldername that has this single script" main :: proc() { world := init_world() defer deinit_world(world) Position :: struct{ val : #simd[4]f32, } Rotation :: struct{ val : #simd[4]f32, } Scale :: struct{ val : #simd[4]f32, } Velocity :: struct{ val : #simd[4]f32, } register(world, Position) register(world, Rotation) register(world, Scale) register(world, Velocity) entity := create_entity(world) entity1 := create_entity(world) entity2 := create_entity(world) entity3 := create_entity(world) entity4 := create_entity(world) velocityx := Velocity{ val = {1.0, 0.0, 0.0, 0.0}, } postion_x := Position{ val = {2.0, 0.0, 0.0, 0.0}, } postion_y := Position{ val = {0.0,3.14,0.0,0.0}, } position_xy := Position{ val = {24.0,7.11,0.0,0.0}, } Quaternion_IDENTITY := Rotation{ val = {0.0,0.0,0.0,1.0}, } add_soa_component(world, entity2, velocityx) add_soa_component(world, entity1, postion_x) add_soa_component(world, entity2, postion_y) add_soa_component(world, entity2, Quaternion_IDENTITY) add_soa_component(world, entity, position_xy) add_soa_component(world, entity, Quaternion_IDENTITY) postion_scale_query := query(world, Velocity, Scale) //register and sort using group position_rotation_query := query(world, Position, Rotation) //register and sort using group position_rotation_query1 := query(world, Position, Rotation) //doesn't register or sort using group uses the cache result postion_scale_query1 := query(world, Velocity, Scale) //doesn't register or sort using group uses the cache result for component_storage, index in run(&position_rotation_query){ mut_component_storage := component_storage if component_storage.entities[index] == 2{ fmt.println("Moving the player entity", component_storage.entities[index] , "Right by 100" ) mut_component_storage.component_a[index].val += {100.0, 0.0, 0.0, 0.0} } fmt.print(component_storage.entities[index], " :\t") fmt.print(component_storage.component_a[index], "\t") fmt.print(component_storage.component_b[index]) fmt.println() } fmt.println("\n") } ``` -------------------------------- ### Initialize and Parse Command Line Arguments with Pix Getopts Source: https://github.com/odin-lang/odin-lang.org/blob/master/content/news/2023-09.md Initializes and configures the getopts parser for command-line arguments, then parses them using os.args. Use this for defining and handling various argument types like flags, optional, and required arguments. ```odin opts := init_opts() defer deinit_opts(&opts) { using optarg_opt add_arg(&opts, "flag", .NO_ARGUMENT) add_arg(&opts, "opt-argument", .OPTIONAL_ARGUMENT) add_arg(&opts, "required", .REQUIRED_ARGUMENT) add_arg(&opts, "h", .NO_ARGUMENT, "help") add_arg(&opts, "m", .OPTIONAL_ARGUMENT, "my_flag_here") } getopt_long(os.args, &opts) for opt in opts.opts { if ! opt.set do continue switch opt.name { case "flag": // Something case "required": // Something else case: // default? Usage! } } ``` -------------------------------- ### Check clang Version Source: https://github.com/odin-lang/odin-lang.org/blob/master/content/docs/install.md To determine the correct C++ standard package to install for atomic.h support, check your clang++ version. Note the version number from the 'Selected GCC installation' line. ```bash clang++ -v ``` -------------------------------- ### If Statement with Initializer Source: https://github.com/odin-lang/odin-lang.org/blob/master/content/docs/overview.md An if statement can start with an initial statement. Variables declared here are scoped to the if statement. ```odin if x := foo(); x < 0 { fmt.println("x is negative") } ``` -------------------------------- ### Odin foreign import examples for different library types and platforms Source: https://github.com/odin-lang/odin-lang.org/blob/master/content/news/binding-to-c.md Illustrates various ways to use `foreign import` for static, shared, and system libraries across Linux and Windows, including specifying paths and system library names. ```odin foreign import foo "foo.a" // static lib in linux, links to /path/to/file/foo.a foreign import foo "foo.so" // shared lib in linux links to /path/to/executable/foo.so foreign import foo "foo.lib" // static/import library in windows, links to /path/to/file/foo.lib foreign import foo "system:foo" // system library (static or shared) in linux. Links to /usr/lib/libfoo.a foreign import foo "system:foo.lib" // system library (static or import) in windows. Links to foo.lib ``` -------------------------------- ### Getting Type Identifiers Source: https://github.com/odin-lang/odin-lang.org/blob/master/content/docs/overview.md Shows how to obtain the `typeid` of a type using `typeid_of` and `type_of`. ```odin a := typeid_of(bool) i: int = 123 b := typeid_of(type_of(i)) ``` -------------------------------- ### SOA Zip and Unzip Source: https://github.com/odin-lang/odin-lang.org/blob/master/content/docs/demo.md Illustrates how to use `soa_zip` to create an SOA slice from multiple regular slices and `soa_unzip` to recover the original slices. Shows iteration over the zipped SOA slice. ```odin x := []i32{1, 3, 9} y := []f32{2, 4, 16} z := []b32{true, false, true} // produce an #soa slice the normal slices passed s := soa_zip(a=x, b=y, c=z) // iterate over the #soa slice for v, i in s { fmt.println(v, i) // exactly the same as s[i] // NOTE: 'v' is NOT a temporary value but has a specialized addressing mode // which means that when accessing v.a etc, it does the correct transformation // internally: // s[i].a === s.a[i] fmt.println(v.a, v.b, v.c) } // Recover the slices from the #soa slice a, b, c := soa_unzip(s) fmt.println(a, b, c) ``` -------------------------------- ### Assembly Procedure for `__get_flags` Source: https://github.com/odin-lang/odin-lang.org/blob/master/content/docs/overview.md An example x86-64 assembly implementation for the `__get_flags` procedure, which retrieves processor flags. ```x86asm bits 64 global __get_flags section .text __get_flags: pushfq pop rax ret ``` -------------------------------- ### Odin Map Initialization with Literal Source: https://github.com/odin-lang/odin-lang.org/blob/master/content/docs/overview.md Demonstrates initializing a map with key-value pairs using a map literal. ```odin m := map[string]int{ "Bob" = 2, "Chloe" = 5, } ``` -------------------------------- ### Array of Structures (AoS) Example Source: https://github.com/odin-lang/odin-lang.org/blob/master/content/docs/overview.md Defines and manipulates a standard Array of Structures (AoS) for Vector3 data. ```odin Vector3 :: struct {x, y, z: f32} N :: 2 v_aos: [N]Vector3 v_aos[0].x = 1 v_aos[0].y = 4 v_aos[0].z = 9 fmt.println(len(v_aos)) fmt.println(v_aos[0]) fmt.println(v_aos[0].x) fmt.println(&v_aos[0].x) v_aos[1] = {0, 3, 4} v_aos[1].x = 2 fmt.println(v_aos[1]) fmt.println(v_aos) ``` -------------------------------- ### Retrieving Type Information Source: https://github.com/odin-lang/odin-lang.org/blob/master/content/docs/overview.md Demonstrates how to get detailed `Type_Info` for a given `typeid` using the `runtime` package. ```odin import "base:runtime" main :: proc() { u := u8(123) id := typeid_of(type_of(u)) info: ^runtime.Type_Info info = type_info_of(id) } ``` -------------------------------- ### Rectangle Fill with Window Sizing Source: https://github.com/odin-lang/odin-lang.org/blob/master/content/news/orca-support.md This snippet demonstrates how to create a window, set its initial size, and handle window resize events to fill the window with a rectangle, respecting margins. It exports `oc_on_resize` to update frame size and `oc_on_frame_refresh` for rendering. ```odin package src import oc "core:sys/orca" surface: oc.surface renderer: oc.canvas_renderer canvas: oc.canvas_context frame_size: oc.vec2 = {500, 500} // Our wanted starting window size main :: proc() { renderer = oc.canvas_renderer_create() surface = oc.canvas_surface_create(renderer) canvas = oc.canvas_context_create() // We provide our wanted dimensions at startup. oc.window_set_size(frame_size) } // Export the 'oc_on_resize' implemented call so it's bound to the Orca application. This will be called whenever the window size changes. @(export) oc_on_resize :: proc "c" (width, height: u32) { frame_size.x = f32(width) frame_size.y = f32(height) } @(export) oc_on_frame_refresh :: proc "c" () { oc.canvas_context_select(canvas) oc.set_color_rgba(1, 1, 1, 1) oc.clear() // Set the color to black and fill the window subtracted by some margin. oc.set_color_rgba(0, 0, 0, 1) SIZE :: 50 width := frame_size.x - SIZE * 2 height := frame_size.y - SIZE * 2 oc.rectangle_fill(SIZE, SIZE, width, height) oc.canvas_render(renderer, canvas, surface) oc.canvas_present(renderer, surface) } ``` -------------------------------- ### Foreign System Interface (Windows) Source: https://github.com/odin-lang/odin-lang.org/blob/master/content/docs/demo.md Demonstrates how to interface with foreign libraries, specifically `kernel32.lib` on Windows, using `foreign import`. It shows default calling conventions and attribute usage. ```odin when ODIN_OS == .Windows { foreign import kernel32 "system:kernel32.lib" } foreign_system :: proc() { fmt.println("\n#foreign system") when ODIN_OS == .Windows { foreign kernel32 { ExitProcess :: proc "stdcall" (exit_code: u32) --- } @(default_calling_convention = "std") foreign kernel32 { @(link_name="GetLastError") get_last_error :: proc() -> i32 --- } @(default_calling_convention = "std") @(link_prefix = "Get") foreign kernel32 { LastError :: proc() -> i32 --- } } } ``` -------------------------------- ### Clone Bootstrap Repository Source: https://github.com/odin-lang/odin-lang.org/blob/master/themes/odin/assets/node_modules/bootstrap/README.md Clone the Bootstrap repository directly from GitHub to get the latest development version. ```bash git clone https://github.com/twbs/bootstrap.git ``` -------------------------------- ### C: Pre-standard Procedure Declaration Source: https://github.com/odin-lang/odin-lang.org/blob/master/content/news/declaration-syntax.md An example of a procedure declaration in pre-standardized C, where types are declared after parameter names. ```c int main(argc, argv) int argc; char *argv[]; { ... } ``` -------------------------------- ### Box2D Physics World Simulation in Odin Source: https://github.com/odin-lang/odin-lang.org/blob/master/content/news/2023-11.md Demonstrates setting up a Box2D physics world, creating static and dynamic bodies, and simulating physics steps. Requires the Box2D library bindings. ```odin package box2d_example import b2 "box2d" import "core:fmt" main :: proc() { world_def := b2.DEFAULT_WORLD_DEF world_def.gravity = b2.Vec2{0, -10} world_id := b2.create_world(&world_def) defer b2.destroy_world(world_id) ground_body_def := b2.DEFAULT_BODY_DEF ground_body_def.position = b2.Vec2{0, -10} ground_body_id := b2.world_create_body(world_id, &ground_body_def) ground_box := b2.make_box(50, 10) ground_shape_def := b2.DEFAULT_SHAPE_DEF b2.body_create_polygon(ground_body_id, &ground_shape_def, &ground_box) body_def := b2.DEFAULT_BODY_DEF body_def.type = .Dynamic body_def.position = b2.Vec2{0, 4} body_id := b2.world_create_body(world_id, &body_def) shape_def := b2.DEFAULT_SHAPE_DEF shape_def.density = 1 shape_def.friction = 0.3 circle: b2.Circle circle.radius = 1 b2.body_create_circle(body_id, &shape_def, &circle) time_step: f32 = 1.0 / 60.0 velocity_iterations: i32 = 6 position_iterations: i32 = 2 for i in 0..<60 { b2.world_step(world_id, time_step, velocity_iterations, position_iterations) position := b2.body_get_position(body_id) angle := b2.body_get_angle(body_id) fmt.println(position, angle) } } ``` -------------------------------- ### Using soa_zip to Combine Slices Source: https://github.com/odin-lang/odin-lang.org/blob/master/content/docs/overview.md Illustrates how `soa_zip` combines multiple slices into a single SoA slice, enabling unified iteration and access. ```odin x := []i32{1, 3, 9} y := []f32{2, 4, 16} z := []b32{true, false, true} // produce an #soa slice with the normal slices passed s := soa_zip(a=x, b=y, c=z) // iterate over the #soa slice for v, i in s { fmt.println(v, i) // exactly the same as s[i] // NOTE: `v` is NOT a temporary value but has a specialized addressing mode // which means that when accessing v.a etc, it does the correct transformation // internally: // s[i].a === s.a[i] fmt.println(v.a, v.b, v.c) } ``` -------------------------------- ### Arbitrary-Precision Mathematics with 'math/big' Source: https://github.com/odin-lang/odin-lang.org/blob/master/content/docs/demo.md Shows how to use the 'math/big' package for arbitrary-precision arithmetic, including generating random primes, packing integers into buffers, and printing large integers with detailed information. Utilizes helper functions for clarity and demonstrates error handling during prime generation. ```odin print_bigint :: proc(name: string, a: ^big.Int, base := i8(10), print_name := true, newline := true, print_extra_info := true) { big.assert_if_nil(a) as, err := big.itoa(a, base) defer delete(as) cb := big.internal_count_bits(a) if print_name { fmt.printf(name) } if err != nil { fmt.printf(" (Error: %v) ", err) } fmt.printf(as) if print_extra_info { fmt.printf(" (base: %v, bits: %v, digits: %v)", base, cb, a.used) } if newline { fmt.println() } } a, b, c, d, e, f, res := &big.Int{}, &big.Int{}, &big.Int{}, &big.Int{}, &big.Int{}, &big.Int{}, &big.Int{} defer big.destroy(a, b, c, d, e, f, res) // How many bits should the random prime be? bits := 64 // Number of Rabin-Miller trials, -1 for automatic. trials := -1 // Default prime generation flags flags := big.Primality_Flags{} err := big.internal_random_prime(a, bits, trials, flags) if err != nil { fmt.printf("Error %v while generating random prime.\n", err) } else { print_bigint("Random Prime A: ", a, 10) fmt.printf("Random number iterations until prime found: %v\n", big.RANDOM_PRIME_ITERATIONS_USED) } // If we want to pack this Int into a buffer of u32, how many do we need? count := big.internal_int_pack_count(a, u32) buf := make([]u32, count) defer delete(buf) written: int written, err = big.internal_int_pack(a, buf) fmt.printf("\nPacked into u32 buf: %v | err: %v | written: %v\n", buf, err, written) ``` -------------------------------- ### Getting Slice Length Source: https://github.com/odin-lang/odin-lang.org/blob/master/content/docs/overview.md The built-in `len` procedure returns the number of elements in a slice. This is useful for determining the size of the slice. ```odin x: []int length_of_x := len(x) ``` -------------------------------- ### C: Procedure Signature Declarations Source: https://github.com/odin-lang/odin-lang.org/blob/master/content/news/declaration-syntax.md Examples of C procedure signatures without identifiers, showing dense and potentially confusing syntax. ```c int main(int, char *[]) int (*)(int, int) int (*qp)(int (*)(int x, int y), int b) ``` -------------------------------- ### Procedure with Simple Sanity Checks Source: https://github.com/odin-lang/odin-lang.org/blob/master/content/docs/overview.md Demonstrates using `where` clauses for basic sanity checks on procedure parameters, such as length and type. ```odin simple_sanity_check :: proc(x: [2]int) where len(x) > 1, type_of(x) == [2]int { fmt.println(x) } ``` -------------------------------- ### Get Source Code Location at Compile-time Source: https://github.com/odin-lang/odin-lang.org/blob/master/content/docs/overview.md The `#location()` directive returns a `runtime.Source_Code_Location` for the current position or a specified entity (variable, procedure). ```odin foo :: proc() {} main :: proc() { n: int fmt.println(#location()) fmt.println(#location(foo)) fmt.println(#location(n)) } ``` -------------------------------- ### Procedure Optimization Mode Source: https://github.com/odin-lang/odin-lang.org/blob/master/content/docs/overview.md The `optimization_mode` attribute allows setting the optimization level for a procedure. This example sets the mode to `favor_size` for the `skip_whitespace` procedure. ```odin @(optimization_mode="favor_size") skip_whitespace :: proc(t: ^Tokenizer) { for { switch t.ch { case ' ', '\t', '\r', '\n': advance_rune(t) case: return } } } ``` -------------------------------- ### Link Suffix for Foreign Procedures Source: https://github.com/odin-lang/odin-lang.org/blob/master/content/docs/overview.md Use `link_suffix` to specify a suffix for foreign procedure names. This example shows `testbar` being linked as `testbar_x86`. ```odin @(link_suffix = "_x86") foreign foo { testbar :: proc(baz: int) --- // This now refers to testbar_x86 } ``` -------------------------------- ### Link Section for Procedure Source: https://github.com/odin-lang/odin-lang.org/blob/master/content/docs/overview.md The `link_section` attribute can also be applied to procedures to specify their link section. This example places `my_procedure` into the `.bar` section. ```odin @(link_section=".bar") my_procedure :: proc "c" () -> i32 { return 1337 } ``` -------------------------------- ### Link Section for Global Variable Source: https://github.com/odin-lang/odin-lang.org/blob/master/content/docs/overview.md The `link_section` attribute specifies the link section for a global variable. This example places `my_global` into the `.foo` section. ```odin @(link_section=".foo") my_global: i32 ``` -------------------------------- ### Exclude File from Linux and Darwin Source: https://github.com/odin-lang/odin-lang.org/blob/master/content/docs/overview.md Use build tags to exclude files from specific platforms. This example excludes the file from both Linux and Darwin. ```odin #+build !linux #+build !darwin package foobar ``` -------------------------------- ### String and Character Literals Source: https://github.com/odin-lang/odin-lang.org/blob/master/content/docs/overview.md Provides examples of basic string and character literals, including escaped special characters and a raw string literal. ```odin "This is a string" 'A' '\n' // newline character "C:\\Windows\\notepad.exe" ``` ```odin `C:\Windows\notepad.exe` ``` -------------------------------- ### Navigate to Odin Folder Source: https://github.com/odin-lang/odin-lang.org/blob/master/content/docs/install.md Change the current directory to the cloned Odin repository folder. ```bash cd Odin ``` -------------------------------- ### Defer Statement Execution Order Source: https://github.com/odin-lang/odin-lang.org/blob/master/content/docs/demo.md Defer statements are executed in the reverse order of their declaration. This example shows how '3', '2', and '1' are printed. ```odin defer if cond { bar() } } // Defer statements are executed in the reverse order that they were declared: { defer fmt.println("1") defer fmt.println("2") defer fmt.println("3") } // Will print 3, 2, and then 1. ```