Objeck Code Examples

Collection of practical code examples demonstrating Objeck's capabilities.

AI developers: See the full AI & ML Developer Guide for comprehensive coverage of OpenAI, Gemini, Ollama, ONNX, OpenCV, and NLP.

Hello World

Basic Hello World

class Hello {
  function : Main(args : String[]) ~ Nil {
    "Hello World"->PrintLine();
  }
}

Unicode Support

class Hello {
  function : Main(args : String[]) ~ Nil {
    "Hello World"->PrintLine();
    "Καλημέρα κόσμε"->PrintLine();
    "こんにちは 世界"->PrintLine();
  }
}

## Web & Networking

HTTP/1.1 HTTPS Client

use Web.HTTP;

class HttpsExample {
  function : Main(args : String[]) ~ Nil {
    # Simple GET
    resp := HttpsClient->QuickGet(Url->New("https://httpbin.org/get"));
    if(resp <> Nil & resp->GetCode() = 200) {
      String->New(resp->GetContent())->PrintLine();
    };

    # POST with JSON
    body := "{\"lang\":\"objeck\"}"->ToByteArray();
    resp := HttpsClient->QuickPost(Url->New("https://httpbin.org/post"),
                                   body, "application/json");
    resp->GetCode()->PrintLine();   # 200
  }
}

HTTP/2 Client

use Web.HTTP;

class Http2Example {
  function : Main(args : String[]) ~ Nil {
    # Persistent connection — all requests share one TLS session
    client := Http2Client->New("httpbin.org");
    if(<>client->IsConnected()) {
      "HTTP/2 unavailable"->ErrorLine();
      return;
    };

    # GET
    resp := client->Get("/get");
    "GET status: {$resp->GetCode()}"->PrintLine();   # 200

    # POST with JSON
    body := "{\"lang\":\"objeck\"}"->ToByteArray();
    resp := client->Post("/post", body, "application/json");
    "POST status: {$resp->GetCode()}"->PrintLine();  # 200

    # Custom header
    client->AddHeader("x-client", "objeck");
    resp := client->Get("/headers");
    String->New(resp->GetContent())->PrintLine();

    # Multiple requests reuse the same connection automatically
    resp1 := client->Get("/ip");
    resp2 := client->Get("/user-agent");

    client->Close();

    # One-liner for quick fire-and-forget requests
    resp := Http2Client->QuickGet(Url->New("https://httpbin.org/get"));
    resp->GetCode()->PrintLine();   # 200
  }
}

HTTP/3 / QUIC Client

use Web.HTTP;

class Http3Example {
  function : Main(args : String[]) ~ Nil {
    # QUIC over UDP — zero round-trip on repeat connections
    client := Http3Client->New("quic.nginx.org");
    if(<>client->IsConnected()) {
      "HTTP/3 unavailable"->ErrorLine();
      return;
    };

    # GET
    resp := client->Get("/");
    "GET status: {$resp->GetCode()}"->PrintLine();   # 200

    # POST
    body := "hello=world"->ToByteArray();
    resp := client->Post("/", body, "application/x-www-form-urlencoded");
    "POST status: {$resp->GetCode()}"->PrintLine();

    # Connection reuse — second request is free (no new handshake)
    resp2 := client->Get("/");

    client->Close();

    # One-liner
    resp := Http3Client->QuickGet(Url->New("https://quic.nginx.org/"));
    resp->GetCode()->PrintLine();   # 200
  }
}

## AI Integration

OpenAI Realtime API

# OpenAI Realtime API - get text AND audio responses
response := Realtime->Respond("How many James Bond movies have been made?",
                              "gpt-4o-realtime-preview-2025-06-03", token);
if(response <> Nil & response->GetFirst() <> Nil & response->GetSecond() <> Nil) {
  # get text
  text := response->GetFirst();
  text_size := text->Size();
  "text: size={$text_size}, text='{$text}'"->PrintLine();

  # get audio
  audio := response->GetSecond();
  audio_bytes := audio->Get();
  audio_bytes_size := audio_bytes->Size();
  "audio: size={$audio_bytes_size}"->PrintLine();

  # play audio
  "---\nplaying..."->PrintLine();
  Mixer->PlayPcm(audio_bytes, 22050, AudioFormat->SDL_AUDIO_S16LSB, 1);
};

Gemini with Schema

# Gemini generate w/ schema
content := Content->New("user")->AddPart(TextPart->New("What are the top 5 cities average snowfall in the Eastern US by city for the past 5 years?"));

# set schema
schema_def := ParameterType->New(["year", "name", "inches"], true);
schema_def->AddProp("year", ParameterType->New(ParameterType->Type->STRING));
schema_def->AddProp("name", ParameterType->New(ParameterType->Type->STRING));
schema_def->AddProp("inches", ParameterType->New(ParameterType->Type->INTEGER));
resp_schema := Pair->New("application/json", schema_def)<String, ParameterType>;

# make query
candidates := Model->GenerateContent("models/gemini-2.5-flash-preview-05-20", content, resp_schema, EndPoint->GetApiKey());
if(candidates <> Nil & <>candidates->IsEmpty()) {
  candidates->First()->GetAllText()->Trim()->PrintLine();
};

OpenAI Image Recognition

# OpenAI image identification
bytes := System.IO.Filesystem.FileReader->ReadBinaryFile("../gemini/thirteen.png");
bytes->Size()->PrintLine();

image := API.OpenAI.ImageQuery->New("What number is this?", bytes, API.OpenAI.ImageQuery->MimeType->PNG);
file_query := Collection.Pair->New("user", image)<String, API.OpenAI.ImageQuery>;

response := Response->Respond("gpt-4o-mini", file_query, token);
if(response = Nil) {
  Response->GetLastError()->ErrorLine();
  return;
};

response->GetText()->PrintLine();

OpenAI Content Moderation

# Check text for policy violations — returns per-category flags and scores
result := Moderation->Check("I love programming!", token);
if(result <> Nil) {
  "Flagged: {$result->IsFlagged()}"->PrintLine();
  if(result->IsFlagged()) {
    score := result->GetScore("violence");
    "violence score: {$score}"->PrintLine();
  };
};

OpenAI Batch Processing

# Submit a batch of requests (up to 50k) for async processing at 50% cost
file_id := "file-abc123";   # upload a .jsonl of requests first
job := Batch->Create(file_id, "/v1/chat/completions", token);
if(job <> Nil) {
  "batch id: {$job->GetId()}"->PrintLine();
  "status: {$job->GetStatus()}"->PrintLine();   # "validating" → "in_progress" → "completed"
};

# Poll later
job := Batch->Get(job->GetId(), token);
if(job->IsComplete()) {
  output_file_id := job->GetOutputFileId();
  "output file: {$output_file_id}"->PrintLine();
};

Gemini Google Search Grounding

# Ground the model's answer in live Google Search results
content := Content->New("user")->AddPart(TextPart->New("What are the latest AI breakthroughs?"));
candidates := Model->GenerateContentWithGrounding("models/gemini-2.0-flash", content, token);
if(candidates <> Nil & <>candidates->IsEmpty()) {
  candidates->First()->GetAllText()->PrintLine();
};

Gemini Batch Embeddings

# Embed multiple texts in one round-trip
texts := Vector->New()<String>;
texts->AddBack("Objeck is a JIT-compiled language");
texts->AddBack("Python is popular for data science");
texts->AddBack("Rust focuses on memory safety");

embeddings := Model->BatchEmbedContent("models/text-embedding-004", texts, token);
each(i : embeddings) {
  emb := embeddings->Get(i);
  dim := emb->Size();
  "  [{$i}] dim={$dim}"->PrintLine();
};

Gemini Files API

# Upload a file for use in model requests
data := FileReader->ReadBinaryFile("document.pdf");
file := FileManager->Upload("my-doc", data, "application/pdf", token);
if(file <> Nil & file->IsActive()) {
  "URI: {$file->GetUri()}"->PrintLine();
};

# List and delete
files := FileManager->List(token);
each(f in files) {
  FileManager->Delete(f->GetName(), token);
};

Gemini Context Caching

# Cache large content server-side to avoid re-tokenizing on every request
content := Content->New("user")->AddPart(TextPart->New(large_system_prompt));
item := CachedContent->Create("models/gemini-1.5-pro-001", content, 300, "my-cache", token);
if(item <> Nil) {
  "name: {$item->GetName()}"->PrintLine();
  "tokens cached: {$item->GetTokenCount()}"->PrintLine();
  "expires: {$item->GetExpireTime()}"->PrintLine();
};

## Computer Vision

Face Detection (ONNX + OpenCV)

use API.OpenCV, API.Onnx, System.IO.Filesystem;

# The OpenCV bundle has no cascade classifier: detect faces with the ONNX
# FaceSession (compile with -lib models,onnx,opencv) and draw the boxes with OpenCV
bytes   := FileReader->ReadBinaryFile("group.jpg");
session := FaceSession->New("det_10g.onnx");
faces   := session->Detect(bytes, 0.5);
count   := faces->GetSize();
"Faces: {$count}"->PrintLine();

image := Image->Load(bytes);
green := Scalar->New(0.0, 255.0, 0.0);
detections := faces->GetDetections();
each(face in detections) {
    image := image->DrawRectangle(face->GetBounds(), green, 2);
};
image->Save("faces.jpg");
session->Close();

OpenCV Image Processing

# Load and process an image
image := Image->Load("photo.jpg");
gray := image->CvtColor(ColorConversionCodes->BGR2GRAY);
blurred := gray->GaussianBlur(5, 5, 0.0);
edges := blurred->Canny(50, 150);
edges->Save("edges.jpg");

## Graphics & GC Visualization

3D — walk through a lit, shadowed scene

gl_walkthrough.obs is a first-person walk around a room built from boxes, with mouse look, sliding collision, one directional light and a shadow map. It uses Game.OpenGL, the 3D framework: OpenGL 3.3 core over SDL2, on Windows, Linux and macOS.

compile: obc -src gl_walkthrough.obs -lib sdl2,sdl_gl
run:     obr gl_walkthrough        # WASD to move, mouse to look, escape to quit

Or let the runner pick the deploy tree, check it is not stale, and pass each demo the assets it needs:

./run_gl.sh gl_walkthrough        # Linux, macOS
.\run_gl.cmd gl_walkthrough       # Windows

The other GL examples are gl_clear (the smallest thing that opens a window — 25 lines), cube_gl (one textured spinning cube), gl_boing (the Boing Ball in 3D, in a room, with a post-process pass) and gl_model (loads gl_crystal.obj and fits it to frame whatever scale it was authored at). programs/examples/gl_fps.obs ships in the distribution.

programs/examples/gl_fps.obs is the framework used the way a game would use it: a lit, shadowed arena you walk around and shoot targets in, with nothing loaded from disk.

It exists to exercise the parts that only show up in combination. Scene->Raycast is the hitscan — a shot is a ray from the camera along the crosshair, and because it reports the nearest hit, a target behind a pillar is protected without the program knowing pillars exist. Scene->SlideMove makes walking into a wall slide along it. A PropBatch draws every post around the edge in one call. A gamepad works if one is plugged in and nothing changes if one is not.

Two traps it ran into, both worth knowing before building anything similar: mark floors and ceilings non-solid (collision is a plan-view test, so a solid floor spans every position in the room and the player cannot move at all), and keep speed * 0.1 under the thickness of your thinnest wall, since SlideMove tests the destination rather than the path swept to reach it.

Boing Ball — live GC/CPU visualizer

The Amiga 1984 Boing Ball recreated with SDL2 (programs/examples/boing_ball.obs): an Amiga-style color-cycled checker sphere with real bounce physics, a Matrix-rain backdrop, a neon OBJECK wordmark, and a HUD reading the VM's live runtime.* monitors (FPS / memory / heap / GC / CPU). Asset-free (it synthesizes its own "boing" WAV) — and a hands-on way to watch the garbage collector work.

compile: obc -src boing_ball.obs -lib sdl2,sdl_game,json,gen_collect
run:     obr boing_ball        # or: obr --gc-threshold=64M boing_ball

Boing Ball MT — multitasking tuning console

boing_ball_mt.obs adds structured concurrency: the ball animates on the main thread while SPACE / W spawn background worker tasks (System.Concurrency.TaskScope) that churn the heap, competing for the cooperative stop-the-world. The HUD shows live thread count, GC pauses, collection counts, and contention; on quit, leaving { scope->JoinAll(); } joins every worker cleanly. A nod to the Amiga demo that ran a terminal while the ball bounced.

compile: obc -src boing_ball_mt.obs -lib sdl2,sdl_game,json,gen_collect,concurrent
run:     obr boing_ball_mt

Checkers — a game, a thinking computer and generated music

programs/examples/checkers/ is a complete checkers game: an SDL2 window at 60 frames a second, ten piece sets drawn from shapes (four crazy creatures and two tech-neo gadget sets), ten computer levels (the library Minimax and MonteCarloTreeSearch play it through a System.AI.GameState wrapper), a hill-climbing learner that tunes the evaluation by self-play, a tournament that proves level N beats level N-1, playful animation, and music generated while you play (hip-hop, modern beats, reggae, techno or classical, with a deep-bass setting and a Markov chain that learns habits from seed phrases, played by a built-in synthesizer or exported as a Standard MIDI File). The engine is checked with perft against the published move counts. See its README.

cd programs/examples/checkers
obc -src checkers_engine.obs,checkers_game.obs,checkers_ai.obs,checkers_logic.obs,checkers_draw.obs,checkers_chars.obs,checkers_fx.obs,checkers_music.obs,checkers_audio.obs,checkers.obs -lib sdl2,sdl_game,ai,json,collect -dest checkers.obe
obr checkers.obe
## More Examples

For complete working examples, visit:

Additional Resources