summaryrefslogtreecommitdiff
path: root/examples
diff options
context:
space:
mode:
authorZuhaitz Méndez Fernández de Aránguiz <zuhaitz@debian>2026-01-25 15:12:12 +0000
committerZuhaitz Méndez Fernández de Aránguiz <zuhaitz@debian>2026-01-25 15:12:12 +0000
commit7d1944ab9d2307f2736afe8520436872db1c7617 (patch)
tree7380a4f148f9ce0b70ed9f02cfa5e8561c783a7a /examples
parent8b720543f538862796fec0ff6b7ea12cb140bf0f (diff)
'let' it be
Diffstat (limited to 'examples')
-rw-r--r--examples/algorithms/binsearch.zc14
-rw-r--r--examples/algorithms/dfs.zc32
-rw-r--r--examples/algorithms/quicksort.zc12
-rw-r--r--examples/algorithms/sieve.zc4
-rw-r--r--examples/collections/word_freq.zc16
-rw-r--r--examples/cpp_interop.zc4
-rw-r--r--examples/data/json_config.zc34
-rw-r--r--examples/data_structures/binary_tree.zc4
-rw-r--r--examples/data_structures/linked_list.zc16
-rw-r--r--examples/data_structures/stack.zc12
-rw-r--r--examples/features/composition.zc4
-rw-r--r--examples/features/comptime_fib.zc10
-rw-r--r--examples/features/showcase.zc10
-rw-r--r--examples/games/zen_craft/main.zc170
-rw-r--r--examples/gpu/cuda-benchmark.zc156
-rw-r--r--examples/gpu/cuda_info.zc10
-rw-r--r--examples/gpu/cuda_vector_add.zc20
-rw-r--r--examples/graphics/mandelbrot.zc34
-rw-r--r--examples/graphics/raylib_demo.zc10
-rw-r--r--examples/networking/echo_server.zc14
-rw-r--r--examples/process/env.zc18
-rw-r--r--examples/scripting/lua/lua.zc2
-rw-r--r--examples/tools/mini_grep.zc64
23 files changed, 335 insertions, 335 deletions
diff --git a/examples/algorithms/binsearch.zc b/examples/algorithms/binsearch.zc
index db1a354..bcddef2 100644
--- a/examples/algorithms/binsearch.zc
+++ b/examples/algorithms/binsearch.zc
@@ -1,11 +1,11 @@
import "std.zc"
fn binary_search(arr: int*, size: isize, target: int) -> isize {
- var low: isize = 0;
- var high: isize = size - 1;
+ let low: isize = 0;
+ let high: isize = size - 1;
while low <= high {
- var mid = low + (high - low) / 2;
+ let mid = low + (high - low) / 2;
if arr[mid] == target {
return mid;
@@ -29,10 +29,10 @@ fn print_array(arr: int*, size: isize) {
}
fn main() {
- var v = Vec<int>::new();
+ let v = Vec<int>::new();
defer v.free();
- var values = [1, 2, 3, 5, 6, 7, 8, 9, 10, 12];
+ let values = [1, 2, 3, 5, 6, 7, 8, 9, 10, 12];
for i in 0..10 {
v.push(values[i]);
}
@@ -40,8 +40,8 @@ fn main() {
"Array: "..;
print_array(v.data, (int)v.len);
- var target = 7;
- var result = binary_search(v.data, (isize)v.len, target);
+ let target = 7;
+ let result = binary_search(v.data, (isize)v.len, target);
"Found {target} at index {result}";
}
diff --git a/examples/algorithms/dfs.zc b/examples/algorithms/dfs.zc
index 054a9d4..2d4670c 100644
--- a/examples/algorithms/dfs.zc
+++ b/examples/algorithms/dfs.zc
@@ -7,7 +7,7 @@ struct Graph {
impl Graph {
fn new(vertices: int) -> Graph {
- var g = Graph {
+ let g = Graph {
num_vertices: vertices,
adj_list: Vec<Vec<int>>::new()
};
@@ -32,10 +32,10 @@ impl Graph {
visited[vertex] = true;
order.push(vertex);
- var neighbors = self.adj_list.data[vertex];
- var neighbor_count = (int)neighbors.len;
+ let neighbors = self.adj_list.data[vertex];
+ let neighbor_count = (int)neighbors.len;
for i in 0..neighbor_count {
- var neighbor = neighbors.data[i];
+ let neighbor = neighbors.data[i];
if !visited[neighbor] {
self._dfs_recursive(neighbor, visited, order);
}
@@ -43,12 +43,12 @@ impl Graph {
}
fn dfs_recursive(self, start: int) -> Vec<int> {
- var order = Vec<int>::new();
+ let order = Vec<int>::new();
if start < 0 || start >= self.num_vertices {
return order;
}
- var visited = Vec<bool>::new();
+ let visited = Vec<bool>::new();
defer visited.free();
for i in 0..self.num_vertices {
visited.push(false);
@@ -59,23 +59,23 @@ impl Graph {
}
fn dfs(self, start: int) -> Vec<int> {
- var order = Vec<int>::new();
+ let order = Vec<int>::new();
if start < 0 || start >= self.num_vertices {
return order;
}
- var visited = Vec<bool>::new();
+ let visited = Vec<bool>::new();
defer visited.free();
for i in 0..self.num_vertices {
visited.push(false);
}
- var stack = Vec<int>::new();
+ let stack = Vec<int>::new();
defer stack.free();
stack.push(start);
while !stack.is_empty() {
- var vertex = stack.pop();
+ let vertex = stack.pop();
if visited.data[vertex] {
continue;
}
@@ -83,10 +83,10 @@ impl Graph {
visited.data[vertex] = true;
order.push(vertex);
- var neighbors = self.adj_list.data[vertex];
- var i = (int)neighbors.len - 1;
+ let neighbors = self.adj_list.data[vertex];
+ let i = (int)neighbors.len - 1;
while i >= 0 {
- var neighbor = neighbors.data[i];
+ let neighbor = neighbors.data[i];
if !visited.data[neighbor] {
stack.push(neighbor);
}
@@ -106,7 +106,7 @@ impl Graph {
}
fn main() {
- var g = Graph::new(6);
+ let g = Graph::new(6);
defer g.free();
g.add_edge(0, 1);
@@ -115,9 +115,9 @@ fn main() {
g.add_edge(1, 4);
g.add_edge(3, 5);
- var order_rec = g.dfs_recursive(0);
+ let order_rec = g.dfs_recursive(0);
defer order_rec.free();
- var order_it = g.dfs(0);
+ let order_it = g.dfs(0);
defer order_it.free();
"DFS recursive order: "..;
diff --git a/examples/algorithms/quicksort.zc b/examples/algorithms/quicksort.zc
index adef038..53395be 100644
--- a/examples/algorithms/quicksort.zc
+++ b/examples/algorithms/quicksort.zc
@@ -2,14 +2,14 @@
import "std.zc"
fn swap(arr: int*, i: isize, j: isize) {
- var temp = arr[i];
+ let temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
fn partition(arr: int*, low: isize, high: isize) -> isize {
- var pivot = arr[high];
- var i = low - 1;
+ let pivot = arr[high];
+ let i = low - 1;
for j in low..high {
if arr[j] < pivot {
@@ -23,7 +23,7 @@ fn partition(arr: int*, low: isize, high: isize) -> isize {
fn quicksort(arr: int*, low: isize, high: isize) {
if low < high {
- var pi = partition(arr, low, high);
+ let pi = partition(arr, low, high);
quicksort(arr, low, pi - 1);
quicksort(arr, pi + 1, high);
}
@@ -39,10 +39,10 @@ fn print_array(arr: int*, size: isize) {
}
fn main() {
- var v = Vec<int>::new();
+ let v = Vec<int>::new();
defer v.free();
- var values = [10, 7, 8, 9, 1, 5, 3, 12, 2, 6];
+ let values = [10, 7, 8, 9, 1, 5, 3, 12, 2, 6];
for i in 0..10 {
v.push(values[i]);
}
diff --git a/examples/algorithms/sieve.zc b/examples/algorithms/sieve.zc
index 25e2c5a..2f5680e 100644
--- a/examples/algorithms/sieve.zc
+++ b/examples/algorithms/sieve.zc
@@ -4,7 +4,7 @@ import "std.zc"
fn main() {
const LIMIT = 50;
- var is_prime: bool[LIMIT];
+ let is_prime: bool[LIMIT];
for i in 0..LIMIT { is_prime[i] = true; }
is_prime[0] = false;
@@ -12,7 +12,7 @@ fn main() {
for p in 2..LIMIT {
if is_prime[p] {
- for (var i = p * p; i < LIMIT; i += p) {
+ for (let i = p * p; i < LIMIT; i += p) {
is_prime[i] = false;
}
}
diff --git a/examples/collections/word_freq.zc b/examples/collections/word_freq.zc
index 781842c..d025542 100644
--- a/examples/collections/word_freq.zc
+++ b/examples/collections/word_freq.zc
@@ -2,19 +2,19 @@
import "std/map.zc"
fn main() {
- var text = "apple banana apple cherry banana apple";
- var delim = " ";
+ let text = "apple banana apple cherry banana apple";
+ let delim = " ";
- var counts = Map<int>::new();
+ let counts = Map<int>::new();
defer counts.free();
- var temp = strdup(text);
+ let temp = strdup(text);
defer free(temp);
- var token = strtok(temp, delim);
+ let token = strtok(temp, delim);
while token != NULL {
if counts.contains(token) {
- var val = counts.get(token).unwrap();
+ let val = counts.get(token).unwrap();
counts.put(token, val + 1);
} else {
counts.put(token, 1);
@@ -27,8 +27,8 @@ fn main() {
for i in 0..counts.capacity() {
if counts.is_slot_occupied(i) {
- var k = counts.key_at(i);
- var v = counts.val_at(i);
+ let k = counts.key_at(i);
+ let v = counts.val_at(i);
println "{k}: {v}";
}
}
diff --git a/examples/cpp_interop.zc b/examples/cpp_interop.zc
index 2f2e033..3db0ea7 100644
--- a/examples/cpp_interop.zc
+++ b/examples/cpp_interop.zc
@@ -25,8 +25,8 @@ fn main() {
cpp_print("Hello from C++!");
- var vec = cpp_make_vector(10, 20, 30);
- var result = cpp_sum_vector(vec);
+ let vec = cpp_make_vector(10, 20, 30);
+ let result = cpp_sum_vector(vec);
"Sum of C++ vector: {result}";
raw {
diff --git a/examples/data/json_config.zc b/examples/data/json_config.zc
index ccfb1a2..d8604d7 100644
--- a/examples/data/json_config.zc
+++ b/examples/data/json_config.zc
@@ -17,24 +17,24 @@ struct Config {
}
fn main() {
- var path = "examples/data/config.json";
+ let path = "examples/data/config.json";
- var content_res = File::read_all(path);
+ let content_res = File::read_all(path);
if content_res.is_err() {
!"Failed to read config file: {content_res.err}";
return 1;
}
- var json_str = content_res.unwrap();
+ let json_str = content_res.unwrap();
- var json_res = JsonValue::parse(json_str.c_str());
+ let json_res = JsonValue::parse(json_str.c_str());
if json_res.is_err() {
!"JSON Parse Error: {json_res.err}";
json_str.free();
return 1;
}
- var root = json_res.unwrap();
+ let root = json_res.unwrap();
defer {
json_str.free();
@@ -47,17 +47,17 @@ fn main() {
return 1;
}
- var config = Config {
+ let config = Config {
server_name: String::new("Unknown"),
port: 0,
logging: false
};
- var obj_map = (*root).object_val;
+ let obj_map = (*root).object_val;
if Map<JsonValue*>::contains(obj_map, "server_name") {
- var opt = Map<JsonValue*>::get(obj_map, "server_name");
- var val = opt.unwrap();
+ let opt = Map<JsonValue*>::get(obj_map, "server_name");
+ let val = opt.unwrap();
if (*val).kind.tag == JsonType::JSON_STRING().tag {
config.server_name.free();
config.server_name = String::new((*val).string_val);
@@ -65,21 +65,21 @@ fn main() {
}
if Map<JsonValue*>::contains(obj_map, "port") {
- var opt = Map<JsonValue*>::get(obj_map, "port");
- var val = opt.unwrap();
+ let opt = Map<JsonValue*>::get(obj_map, "port");
+ let val = opt.unwrap();
if (*val).kind.tag == JsonType::JSON_NUMBER().tag {
config.port = (int)(*val).number_val;
}
}
if Map<JsonValue*>::contains(obj_map, "features") {
- var opt = Map<JsonValue*>::get(obj_map, "features");
- var features = opt.unwrap();
+ let opt = Map<JsonValue*>::get(obj_map, "features");
+ let features = opt.unwrap();
if (*features).kind.tag == JsonType::JSON_OBJECT().tag {
- var f_obj = (*features).object_val;
+ let f_obj = (*features).object_val;
if Map<JsonValue*>::contains(f_obj, "logging") {
- var l_opt = Map<JsonValue*>::get(f_obj, "logging");
- var l = l_opt.unwrap();
+ let l_opt = Map<JsonValue*>::get(f_obj, "logging");
+ let l = l_opt.unwrap();
if (*l).kind.tag == JsonType::JSON_BOOL().tag {
config.logging = (*l).bool_val;
}
@@ -88,7 +88,7 @@ fn main() {
}
"Configuration Loaded:";
- var s_name = config.server_name.c_str();
+ let s_name = config.server_name.c_str();
"Server: {s_name}";
"Port: {config.port}";
"Logging: {config.logging}";
diff --git a/examples/data_structures/binary_tree.zc b/examples/data_structures/binary_tree.zc
index 14e7b3d..86acb21 100644
--- a/examples/data_structures/binary_tree.zc
+++ b/examples/data_structures/binary_tree.zc
@@ -8,7 +8,7 @@ struct Node {
impl Node {
fn new(v: int) -> Self* {
- var n = alloc<Self>();
+ let n = alloc<Self>();
n.value = v;
n.left = NULL;
n.right = NULL;
@@ -71,7 +71,7 @@ impl BST {
}
fn main() {
- var tree = BST::new();
+ let tree = BST::new();
defer tree.free();
"Inserting: 50, 30, 20, 40, 70, 60, 80";
diff --git a/examples/data_structures/linked_list.zc b/examples/data_structures/linked_list.zc
index cb85554..cd16bf5 100644
--- a/examples/data_structures/linked_list.zc
+++ b/examples/data_structures/linked_list.zc
@@ -8,7 +8,7 @@ struct Node {
impl Node {
fn new(v: int) -> Self* {
- var n = alloc<Node>();
+ let n = alloc<Node>();
guard n != NULL else {
"Out of memory!";
return NULL;
@@ -29,7 +29,7 @@ impl LinkedList {
}
fn push(self, v: int) {
- var new_node = Node::new(v);
+ let new_node = Node::new(v);
guard new_node != NULL else { return; }
new_node.next = self.head;
@@ -37,7 +37,7 @@ impl LinkedList {
}
fn print_list(self) {
- var current: Node* = self.head;
+ let current: Node* = self.head;
"["..;
while current != NULL {
"{current.value}"..;
@@ -50,17 +50,17 @@ impl LinkedList {
}
fn free(self) {
- var current: Node* = self.head;
+ let current: Node* = self.head;
while current != NULL {
- autofree var temp = current;
+ autofree let temp = current;
current = current.next;
}
self.head = NULL;
}
fn len(self) -> int {
- var count = 0;
- var current: Node* = self.head;
+ let count = 0;
+ let current: Node* = self.head;
while current != NULL {
count++;
current = current.next;
@@ -70,7 +70,7 @@ impl LinkedList {
}
fn main() {
- var list = LinkedList::new();
+ let list = LinkedList::new();
defer list.free();
"Pushing: 10, 20, 30...";
diff --git a/examples/data_structures/stack.zc b/examples/data_structures/stack.zc
index 8f1fea5..4a8593a 100644
--- a/examples/data_structures/stack.zc
+++ b/examples/data_structures/stack.zc
@@ -43,7 +43,7 @@ impl Stack<T> {
fn main() {
"[Integer Stack]";
- var int_stack = Stack<int>::new();
+ let int_stack = Stack<int>::new();
defer int_stack.free();
"Pushing: 10, 20, 30";
@@ -52,19 +52,19 @@ fn main() {
int_stack.push(30);
"Size: {int_stack.size()}";
- var p = int_stack.peek();
+ let p = int_stack.peek();
"Peek: {p.unwrap()}";
"Popping: "..;
while !int_stack.is_empty() {
- var opt = int_stack.pop();
+ let opt = int_stack.pop();
"{opt.unwrap()} "..;
}
"";
"";
"[String Stack]";
- var str_stack = Stack<String>::new();
+ let str_stack = Stack<String>::new();
defer str_stack.free();
str_stack.push(String::new("First"));
@@ -73,8 +73,8 @@ fn main() {
"Popping: "..;
while !str_stack.is_empty() {
- var opt_s = str_stack.pop();
- var s: String = opt_s.unwrap();
+ let opt_s = str_stack.pop();
+ let s: String = opt_s.unwrap();
"{s.c_str()} "..;
}
"";
diff --git a/examples/features/composition.zc b/examples/features/composition.zc
index 883c348..64fb8e0 100644
--- a/examples/features/composition.zc
+++ b/examples/features/composition.zc
@@ -21,11 +21,11 @@ struct Rigidbody {
fn main() {
// Mixin usage - flattened fields
- var t = Transform{ x: 10.0, y: 5.0, rotation: 90.0 };
+ let t = Transform{ x: 10.0, y: 5.0, rotation: 90.0 };
println "Transform pos: ({t.x}, {t.y})";
// Named usage - nested fields
- var rb = Rigidbody{
+ let rb = Rigidbody{
position: Vector2{x: 0.0, y: 10.0},
velocity: Vector2{x: 1.0, y: 0.0},
mass: 50.0
diff --git a/examples/features/comptime_fib.zc b/examples/features/comptime_fib.zc
index 1ad2898..278ae9f 100644
--- a/examples/features/comptime_fib.zc
+++ b/examples/features/comptime_fib.zc
@@ -1,17 +1,17 @@
fn main() {
comptime {
- var N = 20;
- var fib: long[20];
+ let N = 20;
+ let fib: long[20];
fib[0] = (long)0;
fib[1] = (long)1;
- for var i=2; i<N; i+=1 {
+ for let i=2; i<N; i+=1 {
fib[i] = fib[i-1] + fib[i-2];
}
printf("// Generated Fibonacci Sequence\n");
- printf("var fibs: int[%d] = [", N);
- for var i=0; i<N; i+=1 {
+ printf("let fibs: int[%d] = [", N);
+ for let i=0; i<N; i+=1 {
printf("%ld", fib[i]);
if (i < N-1) printf(", ");
}
diff --git a/examples/features/showcase.zc b/examples/features/showcase.zc
index eca5480..d03fe81 100644
--- a/examples/features/showcase.zc
+++ b/examples/features/showcase.zc
@@ -66,20 +66,20 @@ fn main() {
defer { println "Cleaning up resources..."; }
println "=> Generics and traits.";
- var btn = Button {
+ let btn = Button {
label: "Submit",
width: 120,
height: 40
};
- var container = Container<Button> { item: btn };
+ let container = Container<Button> { item: btn };
- var b = container.get();
+ let b = container.get();
b.draw();
println "";
println "=> Enums and pattern matching.";
- var events: Event[4] = [
+ let events: Event[4] = [
Event::Click(Point { x: 150, y: 300 }),
Event::KeyPress('Z'),
Event::Click(Point { x: 42, y: 0 }),
@@ -92,7 +92,7 @@ fn main() {
println "";
println "=> Lambdas";
- var sum = run_op(10, 20, (a, b) -> a + b);
+ let sum = run_op(10, 20, (a, b) -> a + b);
println "10 + 20 = {sum}";
println "";
}
diff --git a/examples/games/zen_craft/main.zc b/examples/games/zen_craft/main.zc
index 7f86c19..c130e72 100644
--- a/examples/games/zen_craft/main.zc
+++ b/examples/games/zen_craft/main.zc
@@ -30,12 +30,12 @@ extern fn GenImagePerlinNoise(width: int, height: int, offsetX: int, offsetY: in
impl Chunk {
static fn new(x: int, z: int) -> Chunk {
- var c: Chunk;
+ let c: Chunk;
c.x = x;
c.z = z;
// Generate Heightmap
- var heights: int[16][16];
+ let heights: int[16][16];
raw {
Image noise = GenImagePerlinNoise(16, 16, x * 16, z * 16, 0.5f);
@@ -62,7 +62,7 @@ impl Chunk {
for cx in 0..16 {
for cz in 0..16 {
- var h = heights[cx][cz];
+ let h = heights[cx][cz];
for cy in 0..16 {
if cy < h - 1 {
c.blocks[cx][cy][cz] = BLOCK_STONE; // Stone base
@@ -83,11 +83,11 @@ impl Chunk {
for x in 0..16 {
for y in 0..16 {
for z in 0..16 {
- var btype = self.blocks[x][y][z];
+ let btype = self.blocks[x][y][z];
if btype != BLOCK_AIR {
- var _world_x = (float)(self.x * 16 + x);
- var _world_y = (float)y;
- var _world_z = (float)(self.z * 16 + z);
+ let _world_x = (float)(self.x * 16 + x);
+ let _world_y = (float)y;
+ let _world_z = (float)(self.z * 16 + z);
match btype {
BLOCK_DIRT => rl::DrawModel(model_dirt, rl::Vector3{x: _world_x + 0.5, y: _world_y + 0.5, z: _world_z + 0.5}, 1.0, rl::WHITE),
BLOCK_STONE => rl::DrawModel(model_stone, rl::Vector3{x: _world_x + 0.5, y: _world_y + 0.5, z: _world_z + 0.5}, 1.0, rl::WHITE),
@@ -109,12 +109,12 @@ fn get_block(chunks: Chunk*, num_chunks: int, x: int, y: int, z: int) -> int {
if z < 0 || z >= 32 { return BLOCK_AIR; }
// Determine chunk coordinates
- var cx = x / 16;
- var cz = z / 16;
+ let cx = x / 16;
+ let cz = z / 16;
// Determine local block coordinates
- var lx = x % 16;
- var lz = z % 16;
+ let lx = x % 16;
+ let lz = z % 16;
// Find the right chunk
for i in 0..num_chunks {
@@ -129,10 +129,10 @@ fn get_block(chunks: Chunk*, num_chunks: int, x: int, y: int, z: int) -> int {
fn set_block(chunks: Chunk*, num_chunks: int, x: int, y: int, z: int, type: int) {
if y < 0 || y >= 16 { return; }
- var cx = x / 16;
- var cz = z / 16;
- var lx = x % 16;
- var lz = z % 16;
+ let cx = x / 16;
+ let cz = z / 16;
+ let lx = x % 16;
+ let lz = z % 16;
for i in 0..num_chunks {
if chunks[i].x == cx && chunks[i].z == cz {
@@ -153,19 +153,19 @@ struct RaycastHit {
}
fn raycast(chunks: Chunk*, num_chunks: int, ox: float, oy: float, oz: float, dx: float, dy: float, dz: float, max_dist: float) -> RaycastHit {
- var r: RaycastHit;
+ let r: RaycastHit;
r.hit = 0;
- var x = ox;
- var y = oy;
- var z = oz;
+ let x = ox;
+ let y = oy;
+ let z = oz;
- var step = 0.05;
- var dist = 0.0;
+ let step = 0.05;
+ let dist = 0.0;
- var last_x = (int)floor(x);
- var last_y = (int)floor(y);
- var last_z = (int)floor(z);
+ let last_x = (int)floor(x);
+ let last_y = (int)floor(y);
+ let last_z = (int)floor(z);
while dist < max_dist {
x += dx * step;
@@ -173,9 +173,9 @@ fn raycast(chunks: Chunk*, num_chunks: int, ox: float, oy: float, oz: float, dx:
z += dz * step;
dist += step;
- var ix = (int)floor(x);
- var iy = (int)floor(y);
- var iz = (int)floor(z);
+ let ix = (int)floor(x);
+ let iy = (int)floor(y);
+ let iz = (int)floor(z);
if get_block(chunks, num_chunks, ix, iy, iz) != BLOCK_AIR {
r.hit = 1;
@@ -210,14 +210,14 @@ fn raycast(chunks: Chunk*, num_chunks: int, ox: float, oy: float, oz: float, dx:
extern fn DrawCubeTexture(texture: rl::Texture2D, position: rl::Vector3, width: float, height: float, length: float, color: rl::Color);
// Textures & Models
-var model_dirt: rl::Model;
-var model_grass: rl::Model;
-var model_stone: rl::Model;
-var tex_sun: rl::Texture2D;
-var tex_moon: rl::Texture2D;
+let model_dirt: rl::Model;
+let model_grass: rl::Model;
+let model_stone: rl::Model;
+let tex_sun: rl::Texture2D;
+let tex_moon: rl::Texture2D;
fn load_texture_from_memory(_data: char*, _len: int) -> rl::Texture2D {
- var tex: rl::Texture2D;
+ let tex: rl::Texture2D;
raw {
Image img = LoadImageFromMemory(".png", (unsigned char*)_data, _len);
tex = LoadTextureFromImage(img);
@@ -227,20 +227,20 @@ fn load_texture_from_memory(_data: char*, _len: int) -> rl::Texture2D {
}
fn init_textures() {
- var dirt_data = embed "examples/games/zen_craft/assets/dirt.png";
- var grass_data = embed "examples/games/zen_craft/assets/grass_side.png";
- var stone_data = embed "examples/games/zen_craft/assets/stone.png";
- var sun_data = embed "examples/games/zen_craft/assets/sun.png";
- var moon_data = embed "examples/games/zen_craft/assets/moon.png";
-
- var _tex_dirt = load_texture_from_memory(dirt_data.data, dirt_data.len);
- var _tex_grass = load_texture_from_memory(grass_data.data, grass_data.len);
- var _tex_stone = load_texture_from_memory(stone_data.data, stone_data.len);
+ let dirt_data = embed "examples/games/zen_craft/assets/dirt.png";
+ let grass_data = embed "examples/games/zen_craft/assets/grass_side.png";
+ let stone_data = embed "examples/games/zen_craft/assets/stone.png";
+ let sun_data = embed "examples/games/zen_craft/assets/sun.png";
+ let moon_data = embed "examples/games/zen_craft/assets/moon.png";
+
+ let _tex_dirt = load_texture_from_memory(dirt_data.data, dirt_data.len);
+ let _tex_grass = load_texture_from_memory(grass_data.data, grass_data.len);
+ let _tex_stone = load_texture_from_memory(stone_data.data, stone_data.len);
tex_sun = load_texture_from_memory(sun_data.data, sun_data.len);
tex_moon = load_texture_from_memory(moon_data.data, moon_data.len);
// Create Models
- var mesh = rl::GenMeshCube(1.0, 1.0, 1.0);
+ let mesh = rl::GenMeshCube(1.0, 1.0, 1.0);
model_dirt = rl::LoadModelFromMesh(mesh);
model_grass = rl::LoadModelFromMesh(mesh);
model_stone = rl::LoadModelFromMesh(mesh);
@@ -256,7 +256,7 @@ fn draw_sky(camera: rl::Camera3D) {
// Disable Depth Mask to draw sky behind everything
rl::BeginMode3D(camera);
// Simple Fixed Sun Position or billboard
- var sun_pos = rl::Vector3{x: camera.position.x + 20.0, y: camera.position.y + 40.0, z: camera.position.z + 20.0};
+ let sun_pos = rl::Vector3{x: camera.position.x + 20.0, y: camera.position.y + 40.0, z: camera.position.z + 20.0};
raw {
DrawBillboard(camera, tex_sun, sun_pos, 10.0f, WHITE);
@@ -277,12 +277,12 @@ struct Player {
}
fn check_collision(chunks: Chunk*, num_chunks: int, x: float, y: float, z: float, w: float, h: float) -> int {
- var min_x = (int)floor(x - w/2.0);
- var max_x = (int)floor(x + w/2.0);
- var min_y = (int)floor(y);
- var max_y = (int)floor(y + h);
- var min_z = (int)floor(z - w/2.0);
- var max_z = (int)floor(z + w/2.0);
+ let min_x = (int)floor(x - w/2.0);
+ let max_x = (int)floor(x + w/2.0);
+ let min_y = (int)floor(y);
+ let max_y = (int)floor(y + h);
+ let min_z = (int)floor(z - w/2.0);
+ let max_z = (int)floor(z + w/2.0);
for ix in min_x..max_x+1 {
for iy in min_y..max_y+1 {
@@ -298,7 +298,7 @@ fn check_collision(chunks: Chunk*, num_chunks: int, x: float, y: float, z: float
impl Player {
static fn new(x: float, y: float, z: float) -> Player {
- var p: Player;
+ let p: Player;
p.x = x;
p.y = y;
p.z = z;
@@ -320,7 +320,7 @@ impl Player {
fn update(self, chunks: Chunk*, num_chunks: int, dt: float) {
// Mouse look
- var mouse_delta = rl::GetMouseDelta();
+ let mouse_delta = rl::GetMouseDelta();
self.yaw += mouse_delta.x * 0.003;
self.pitch += mouse_delta.y * 0.003;
@@ -328,22 +328,22 @@ impl Player {
if self.pitch < -1.5 { self.pitch = -1.5; }
// Movement input
- var dx = 0.0;
- var dz = 0.0;
+ let dx = 0.0;
+ let dz = 0.0;
if rl::IsKeyDown(rl::KEY_W) { dx += 1.0; }
if rl::IsKeyDown(rl::KEY_S) { dx -= 1.0; }
if rl::IsKeyDown(rl::KEY_A) { dz -= 1.0; }
if rl::IsKeyDown(rl::KEY_D) { dz += 1.0; }
- var fx = cos(self.yaw);
- var fz = sin(self.yaw);
- var rx = -sin(self.yaw);
- var rz = cos(self.yaw);
+ let fx = cos(self.yaw);
+ let fz = sin(self.yaw);
+ let rx = -sin(self.yaw);
+ let rz = cos(self.yaw);
- var move_x = fx * dx + rx * dz;
- var move_z = fz * dx + rz * dz;
+ let move_x = fx * dx + rx * dz;
+ let move_z = fz * dx + rz * dz;
- var mlen = sqrt(move_x*move_x + move_z*move_z);
+ let mlen = sqrt(move_x*move_x + move_z*move_z);
if mlen > 0.001 {
move_x /= mlen;
move_z /= mlen;
@@ -365,8 +365,8 @@ impl Player {
}
// Physics integration (Separate Axes)
- var box_w = 0.6;
- var box_h = 1.8;
+ let box_w = 0.6;
+ let box_h = 1.8;
// X axis
self.x += self.vx * dt;
@@ -396,9 +396,9 @@ impl Player {
}
// Sync Camera
- var view_x = cos(self.yaw) * cos(self.pitch);
- var view_z = sin(self.yaw) * cos(self.pitch);
- var view_y = -sin(self.pitch);
+ let view_x = cos(self.yaw) * cos(self.pitch);
+ let view_z = sin(self.yaw) * cos(self.pitch);
+ let view_y = -sin(self.pitch);
self.camera.position.x = self.x;
self.camera.position.y = self.y + 1.6;
@@ -421,11 +421,11 @@ fn main() {
init_textures();
// Initialize Player
- var p = Player::new(10.0, 10.0, 10.0);
- var selected_block = BLOCK_STONE;
+ let p = Player::new(10.0, 10.0, 10.0);
+ let selected_block = BLOCK_STONE;
// Generate Chunks
- var chunks: Chunk[4];
+ let chunks: Chunk[4];
chunks[0] = Chunk::new(0, 0);
chunks[1] = Chunk::new(1, 0);
chunks[2] = Chunk::new(0, 1);
@@ -434,7 +434,7 @@ fn main() {
rl::DisableCursor(); // Capture mouse
while !rl::WindowShouldClose() {
- var dt: float = rl::GetFrameTime();
+ let dt: float = rl::GetFrameTime();
(&p).update(&chunks[0], 4, dt);
// Block selection input
@@ -452,25 +452,25 @@ fn main() {
// Render chunks
for i in 0..4 {
- var c: Chunk* = &chunks[i];
+ let c: Chunk* = &chunks[i];
c.draw();
}
// Block interaction
- var screen_center = rl::Vector2{
+ let screen_center = rl::Vector2{
x: (float)rl::GetScreenWidth() / 2.0,
y: (float)rl::GetScreenHeight() / 2.0
};
- var pick_ray = rl::GetScreenToWorldRay(screen_center, p.camera);
+ let pick_ray = rl::GetScreenToWorldRay(screen_center, p.camera);
- var hit = raycast(&chunks[0], 4, pick_ray.position.x, pick_ray.position.y, pick_ray.position.z,
+ let hit = raycast(&chunks[0], 4, pick_ray.position.x, pick_ray.position.y, pick_ray.position.z,
pick_ray.direction.x, pick_ray.direction.y, pick_ray.direction.z, 5.0);
if hit.hit != 0 {
// Draw selection
- var hx = (float)hit.x;
- var hy = (float)hit.y;
- var hz = (float)hit.z;
+ let hx = (float)hit.x;
+ let hy = (float)hit.y;
+ let hz = (float)hit.z;
// Draw slight offset wireframe
rl::DrawCubeWires(rl::Vector3{x: hx + 0.5, y: hy + 0.5, z: hz + 0.5}, 1.01, 1.01, 1.01, rl::BLACK);
@@ -480,14 +480,14 @@ fn main() {
set_block(&chunks[0], 4, hit.x, hit.y, hit.z, BLOCK_AIR);
}
else if rl::IsMouseButtonPressed(rl::MOUSE_BUTTON_RIGHT) {
- var nx = hit.x + hit.face_x;
- var ny = hit.y + hit.face_y;
- var nz = hit.z + hit.face_z;
+ let nx = hit.x + hit.face_x;
+ let ny = hit.y + hit.face_y;
+ let nz = hit.z + hit.face_z;
// Don't place inside player (Simple check)
- var dist_x = p.x - ((float)nx + 0.5);
- var dist_y = p.y + 1.6 - ((float)ny + 0.5); // Eye pos vs block center
- var dist_z = p.z - ((float)nz + 0.5);
+ let dist_x = p.x - ((float)nx + 0.5);
+ let dist_y = p.y + 1.6 - ((float)ny + 0.5); // Eye pos vs block center
+ let dist_z = p.z - ((float)nz + 0.5);
if (dist_x*dist_x + dist_y*dist_y + dist_z*dist_z) > 2.0 {
set_block(&chunks[0], 4, nx, ny, nz, selected_block);
}
@@ -497,8 +497,8 @@ fn main() {
rl::EndMode3D();
// Draw HUD
- var sw = rl::GetScreenWidth();
- var sh = rl::GetScreenHeight();
+ let sw = rl::GetScreenWidth();
+ let sh = rl::GetScreenHeight();
rl::DrawRectangle(sw/2 - 5, sh/2 - 1, 10, 2, rl::RED); // Horizontal
rl::DrawRectangle(sw/2 - 1, sh/2 - 5, 2, 10, rl::RED); // Vertical
diff --git a/examples/gpu/cuda-benchmark.zc b/examples/gpu/cuda-benchmark.zc
index d426e10..cea326e 100644
--- a/examples/gpu/cuda-benchmark.zc
+++ b/examples/gpu/cuda-benchmark.zc
@@ -11,11 +11,11 @@ import "std/mem.zc"
@global
fn matrix_multiply_kernel(A: float*, B: float*, C: float*, N: int) {
- var row = block_id_y() * block_dim_y() + thread_id_y();
- var col = block_id_x() * block_dim_x() + thread_id_x();
+ let row = block_id_y() * block_dim_y() + thread_id_y();
+ let col = block_id_x() * block_dim_x() + thread_id_x();
if row < N && col < N {
- var sum = 0.0f;
+ let sum = 0.0f;
for k in 0..N {
sum = sum + A[row * N + k] * B[k * N + col];
}
@@ -29,26 +29,26 @@ fn matrix_multiply_kernel(A: float*, B: float*, C: float*, N: int) {
@global
fn monte_carlo_pi_kernel(results: float*, num_samples: u64, seed: u64) {
- var idx = block_id_x() * block_dim_x() + thread_id_x();
- var total_threads = grid_dim_x() * block_dim_x();
+ let idx = block_id_x() * block_dim_x() + thread_id_x();
+ let total_threads = grid_dim_x() * block_dim_x();
- var local_count: u64 = 0;
- var samples_per_thread = num_samples / total_threads;
+ let local_count: u64 = 0;
+ let samples_per_thread = num_samples / total_threads;
// Simple random number generator
- var rand_state = seed + idx;
+ let rand_state = seed + idx;
for i in 0..samples_per_thread {
// Generate random x and y in [0, 1]
- var a: u64 = 1103515245u64;
- var b: u64 = 12345u64;
- var m: u64 = 2147483648u64;
+ let a: u64 = 1103515245u64;
+ let b: u64 = 12345u64;
+ let m: u64 = 2147483648u64;
rand_state = (a * rand_state + b) % m;
- var x = (float)rand_state / 2147483648.0f;
+ let x = (float)rand_state / 2147483648.0f;
rand_state = (a * rand_state + b) % m;
- var y = (float)rand_state / 2147483648.0f;
+ let y = (float)rand_state / 2147483648.0f;
// Check if point is inside quarter circle
if x * x + y * y <= 1.0f {
@@ -66,30 +66,30 @@ fn monte_carlo_pi_kernel(results: float*, num_samples: u64, seed: u64) {
fn nbody_kernel(x: float*, y: float*, z: float*,
vx: float*, vy: float*, vz: float*,
N: int, dt: float) {
- var i = thread_id();
+ let i = thread_id();
if i < N {
- var ax = 0.0f;
- var ay = 0.0f;
- var az = 0.0f;
- var xi = x[i];
- var yi = y[i];
- var zi = z[i];
+ let ax = 0.0f;
+ let ay = 0.0f;
+ let az = 0.0f;
+ let xi = x[i];
+ let yi = y[i];
+ let zi = z[i];
// Calculate gravitational forces from all other bodies
for j in 0..N {
if i != j {
- var dx = x[j] - xi;
- var dy = y[j] - yi;
- var dz = z[j] - zi;
-
- var dx2 = dx * dx;
- var dy2 = dy * dy;
- var dz2 = dz * dz;
- var softening: float = 0.0000000001f;
- var dist_sqr = dx2 + dy2 + dz2 + softening;
- var dist = sqrtf(dist_sqr);
- var force = 1.0f / (dist_sqr * dist);
+ let dx = x[j] - xi;
+ let dy = y[j] - yi;
+ let dz = z[j] - zi;
+
+ let dx2 = dx * dx;
+ let dy2 = dy * dy;
+ let dz2 = dz * dz;
+ let softening: float = 0.0000000001f;
+ let dist_sqr = dx2 + dy2 + dz2 + softening;
+ let dist = sqrtf(dist_sqr);
+ let force = 1.0f / (dist_sqr * dist);
ax = ax + (force * dx);
ay = ay + (force * dy);
@@ -115,27 +115,27 @@ fn nbody_kernel(x: float*, y: float*, z: float*,
@global
fn mandelbrot_kernel(output: int*, width: int, height: int, max_iter: int) {
- var px = block_id_x() * block_dim_x() + thread_id_x();
- var py = block_id_y() * block_dim_y() + thread_id_y();
+ let px = block_id_x() * block_dim_x() + thread_id_x();
+ let py = block_id_y() * block_dim_y() + thread_id_y();
if px < width && py < height {
// Map pixel to complex plane
- var x0 = ((float)px / (float)width) * 3.5f - 2.5f;
- var y0 = ((float)py / (float)height) * 2.0f - 1.0f;
+ let x0 = ((float)px / (float)width) * 3.5f - 2.5f;
+ let y0 = ((float)py / (float)height) * 2.0f - 1.0f;
- var x = 0.0f;
- var y = 0.0f;
- var iter = 0;
+ let x = 0.0f;
+ let y = 0.0f;
+ let iter = 0;
// Iterate z = z^2 + c
for i in 0..max_iter {
- var x2 = x * x;
- var y2 = y * y;
+ let x2 = x * x;
+ let y2 = y * y;
if (x2 + y2) > 4.0f {
break;
}
- var xtemp = x2 - y2 + x0;
- var xy2 = 2.0f * x * y;
+ let xtemp = x2 - y2 + x0;
+ let xy2 = 2.0f * x * y;
y = xy2 + y0;
x = xtemp;
iter = iter + 1;
@@ -150,7 +150,7 @@ fn mandelbrot_kernel(output: int*, width: int, height: int, max_iter: int) {
fn print_gpu_info() {
- var device_count = cuda_device_count();
+ let device_count = cuda_device_count();
"Found {device_count} CUDA device(s)\n";
}
@@ -161,13 +161,13 @@ fn print_gpu_info() {
fn benchmark_matrix_multiply(N: int) {
"Benchmark 1: Matrix Multiplication ({N}x{N}) ";
- var size = N * N;
+ let size = N * N;
// Allocate host memory
"-> Allocating host memory...";
- var h_A = alloc_n<float>(size);
- var h_B = alloc_n<float>(size);
- var h_C = alloc_n<float>(size);
+ let h_A = alloc_n<float>(size);
+ let h_B = alloc_n<float>(size);
+ let h_C = alloc_n<float>(size);
defer free(h_A);
defer free(h_B);
defer free(h_C);
@@ -181,9 +181,9 @@ fn benchmark_matrix_multiply(N: int) {
// Allocate device memory
"-> Allocating device memory...";
- var d_A = cuda_alloc<float>(size);
- var d_B = cuda_alloc<float>(size);
- var d_C = cuda_alloc<float>(size);
+ let d_A = cuda_alloc<float>(size);
+ let d_B = cuda_alloc<float>(size);
+ let d_C = cuda_alloc<float>(size);
defer cuda_free(d_A);
defer cuda_free(d_B);
defer cuda_free(d_C);
@@ -195,12 +195,12 @@ fn benchmark_matrix_multiply(N: int) {
// Configure grid
const BLOCK_SIZE = 16;
- var blocks_per_grid = (N + BLOCK_SIZE - 1) / BLOCK_SIZE;
+ let blocks_per_grid = (N + BLOCK_SIZE - 1) / BLOCK_SIZE;
"-> Launching kernel: {blocks_per_grid}x{blocks_per_grid} blocks, {BLOCK_SIZE}x{BLOCK_SIZE} threads each";
" GPU IS NOW WORKING HARD - Check nvtop!\n";
- var start = clock();
+ let start = clock();
// Run multiple iterations to keep GPU busy
for iter in 0..10 {
@@ -212,7 +212,7 @@ fn benchmark_matrix_multiply(N: int) {
" Iteration {iter + 1}/10 complete";
}
- var elapsed = (clock() - start) / CLOCKS_PER_SEC;
+ let elapsed = (clock() - start) / CLOCKS_PER_SEC;
" Completed in {elapsed} seconds\n";
// Copy result back
@@ -234,23 +234,23 @@ fn benchmark_monte_carlo_pi(num_samples: u64) {
const BLOCK_SIZE = 256;
const NUM_BLOCKS = 1024;
- var total_threads = BLOCK_SIZE * NUM_BLOCKS;
+ let total_threads = BLOCK_SIZE * NUM_BLOCKS;
// Allocate memory
- var h_results = alloc_n<float>(total_threads);
+ let h_results = alloc_n<float>(total_threads);
defer free(h_results);
- var d_results = cuda_alloc<float>(total_threads);
+ let d_results = cuda_alloc<float>(total_threads);
defer cuda_free(d_results);
"-> Launching kernel: {NUM_BLOCKS} blocks x {BLOCK_SIZE} threads";
" GPU IS NOW WORKING HARD - Check nvtop!\n";
- var start = clock();
+ let start = clock();
// Run many iterations
for iter in 0..100 {
- var seed = (u64)time(NULL) + (u64)iter;
+ let seed = (u64)time(NULL) + (u64)iter;
launch monte_carlo_pi_kernel(d_results, num_samples, seed) with {
grid: NUM_BLOCKS,
@@ -263,19 +263,19 @@ fn benchmark_monte_carlo_pi(num_samples: u64) {
}
}
- var elapsed = (clock() - start) / CLOCKS_PER_SEC;
+ let elapsed = (clock() - start) / CLOCKS_PER_SEC;
"\n Completed in {elapsed} seconds\n";
// Copy results and calculate Pi
cuda_copy_to_host(h_results, d_results, total_threads * sizeof(float));
- var total_inside: u64 = 0;
+ let total_inside: u64 = 0;
for i in 0..total_threads {
total_inside = total_inside + (u64)h_results[i];
}
- var pi_estimate = 4.0 * (double)total_inside / (double)num_samples;
- var error = fabs(pi_estimate - 3.14159265359);
+ let pi_estimate = 4.0 * (double)total_inside / (double)num_samples;
+ let error = fabs(pi_estimate - 3.14159265359);
"-> Results:";
" Estimated Pi: {pi_estimate}";
@@ -294,12 +294,12 @@ fn benchmark_nbody(num_bodies: int, num_steps: int) {
"-> Simulating {num_bodies} bodies for {num_steps} steps";
// Allocate host memory
- var h_x = alloc_n<float>(num_bodies);
- var h_y = alloc_n<float>(num_bodies);
- var h_z = alloc_n<float>(num_bodies);
- var h_vx = alloc_n<float>(num_bodies);
- var h_vy = alloc_n<float>(num_bodies);
- var h_vz = alloc_n<float>(num_bodies);
+ let h_x = alloc_n<float>(num_bodies);
+ let h_y = alloc_n<float>(num_bodies);
+ let h_z = alloc_n<float>(num_bodies);
+ let h_vx = alloc_n<float>(num_bodies);
+ let h_vy = alloc_n<float>(num_bodies);
+ let h_vz = alloc_n<float>(num_bodies);
defer free(h_x);
defer free(h_y);
defer free(h_z);
@@ -321,12 +321,12 @@ fn benchmark_nbody(num_bodies: int, num_steps: int) {
// Allocate device memory
"-> Allocating device memory...";
- var d_x = cuda_alloc<float>(num_bodies);
- var d_y = cuda_alloc<float>(num_bodies);
- var d_z = cuda_alloc<float>(num_bodies);
- var d_vx = cuda_alloc<float>(num_bodies);
- var d_vy = cuda_alloc<float>(num_bodies);
- var d_vz = cuda_alloc<float>(num_bodies);
+ let d_x = cuda_alloc<float>(num_bodies);
+ let d_y = cuda_alloc<float>(num_bodies);
+ let d_z = cuda_alloc<float>(num_bodies);
+ let d_vx = cuda_alloc<float>(num_bodies);
+ let d_vy = cuda_alloc<float>(num_bodies);
+ let d_vz = cuda_alloc<float>(num_bodies);
defer cuda_free(d_x);
defer cuda_free(d_y);
defer cuda_free(d_z);
@@ -343,13 +343,13 @@ fn benchmark_nbody(num_bodies: int, num_steps: int) {
cuda_copy_to_device(d_vz, h_vz, num_bodies * sizeof(float));
const BLOCK_SIZE = 256;
- var num_blocks = (num_bodies + BLOCK_SIZE - 1) / BLOCK_SIZE;
- var dt = 0.01f;
+ let num_blocks = (num_bodies + BLOCK_SIZE - 1) / BLOCK_SIZE;
+ let dt = 0.01f;
"-> Launching simulation: {num_blocks} blocks x {BLOCK_SIZE} threads";
" GPU IS NOW WORKING HARD - Check nvtop!\n";
- var start = clock();
+ let start = clock();
for step in 0..num_steps {
launch nbody_kernel(d_x, d_y, d_z, d_vx, d_vy, d_vz, num_bodies, dt) with {
@@ -363,7 +363,7 @@ fn benchmark_nbody(num_bodies: int, num_steps: int) {
}
}
- var elapsed = (clock() - start) / CLOCKS_PER_SEC;
+ let elapsed = (clock() - start) / CLOCKS_PER_SEC;
"\n Completed in {elapsed} seconds\n";
// Copy results back
diff --git a/examples/gpu/cuda_info.zc b/examples/gpu/cuda_info.zc
index 7e832d1..55d2042 100644
--- a/examples/gpu/cuda_info.zc
+++ b/examples/gpu/cuda_info.zc
@@ -3,13 +3,13 @@ import "std/cuda.zc"
import "std/string.zc"
fn main() {
- var count = cuda_device_count();
+ let count = cuda_device_count();
"---------------------------";
"CUDA Device Count: {count}";
"---------------------------";
if (count > 0) {
- var props = cuda_device_properties(0);
+ let props = cuda_device_properties(0);
"Device Name: {props.name.vec.data}";
"Total Global Mem: {props.total_global_mem}";
@@ -20,13 +20,13 @@ fn main() {
props.name.free();
- var driver = cuda_driver_version();
- var runtime = cuda_runtime_version();
+ let driver = cuda_driver_version();
+ let runtime = cuda_runtime_version();
"Driver Version: {driver}";
"Runtime Version: {runtime}";
- var mem = cuda_mem_info();
+ let mem = cuda_mem_info();
"Free Mem: {mem.free}";
"Total Mem: {mem.total}";
}
diff --git a/examples/gpu/cuda_vector_add.zc b/examples/gpu/cuda_vector_add.zc
index de75a74..d1f896a 100644
--- a/examples/gpu/cuda_vector_add.zc
+++ b/examples/gpu/cuda_vector_add.zc
@@ -8,7 +8,7 @@ import "std/mem.zc"
@global
fn add_kernel(a: float*, b: float*, c: float*, n: int) {
- var i = thread_id();
+ let i = thread_id();
if i < n {
c[i] = a[i] + b[i];
}
@@ -20,9 +20,9 @@ fn main() {
"=> Zen C CUDA Vector Addition";
"-> Vector size: {N} elements";
- var h_a = alloc_n<float>(N);
- var h_b = alloc_n<float>(N);
- var h_c = alloc_n<float>(N);
+ let h_a = alloc_n<float>(N);
+ let h_b = alloc_n<float>(N);
+ let h_c = alloc_n<float>(N);
defer free(h_a);
defer free(h_b);
defer free(h_c);
@@ -33,9 +33,9 @@ fn main() {
}
"-> Allocating device memory...";
- var d_a = cuda_alloc<float>(N);
- var d_b = cuda_alloc<float>(N);
- var d_c = cuda_alloc<float>(N);
+ let d_a = cuda_alloc<float>(N);
+ let d_b = cuda_alloc<float>(N);
+ let d_c = cuda_alloc<float>(N);
defer cuda_free(d_a);
defer cuda_free(d_b);
defer cuda_free(d_c);
@@ -44,7 +44,7 @@ fn main() {
cuda_copy_to_device(d_b, h_b, N * sizeof(float));
const BLOCK_SIZE = 256;
- var num_blocks = (N + BLOCK_SIZE - 1) / BLOCK_SIZE;
+ let num_blocks = (N + BLOCK_SIZE - 1) / BLOCK_SIZE;
"-> Launching: {num_blocks} blocks x {BLOCK_SIZE} threads";
@@ -58,9 +58,9 @@ fn main() {
cuda_copy_to_host(h_c, d_c, N * sizeof(float));
"-> Verifying...";
- var ok: int = 1;
+ let ok: int = 1;
for i in 0..10 {
- var expected = h_a[i] + h_b[i];
+ let expected = h_a[i] + h_b[i];
if h_c[i] != expected {
!"-> Mismatch at {i}";
ok = 0;
diff --git a/examples/graphics/mandelbrot.zc b/examples/graphics/mandelbrot.zc
index f3fa4bd..aca94ba 100644
--- a/examples/graphics/mandelbrot.zc
+++ b/examples/graphics/mandelbrot.zc
@@ -31,8 +31,8 @@ fn pick_char(iter: int, max_iter: int, edge_chars: char[], edge_count: int) -> c
if (iter >= max_iter) { return ' '; }
if (iter <= 0) { return edge_chars[0]; }
- var t: float = ((float)iter) / ((float)max_iter);
- var idx: int = (int)(t * ((float)(edge_count - 1)));
+ let t: float = ((float)iter) / ((float)max_iter);
+ let idx: int = (int)(t * ((float)(edge_count - 1)));
if (idx < 0) { idx = 0; }
if (idx >= edge_count) { idx = edge_count - 1; }
@@ -41,36 +41,36 @@ fn pick_char(iter: int, max_iter: int, edge_chars: char[], edge_count: int) -> c
}
fn main() {
- var width: int = 120;
- var height: int = 40;
- var max_iter: int = 200;
+ let width: int = 120;
+ let height: int = 40;
+ let max_iter: int = 200;
- var edge_chars: char[12] = [ '#', '@', '%', '8', '&', '*', '+', '=', '-', ':', '.', ',' ];
- var edge_count: int = 12;
+ let edge_chars: char[12] = [ '#', '@', '%', '8', '&', '*', '+', '=', '-', ':', '.', ',' ];
+ let edge_count: int = 12;
- var min_re: float = -2.2;
- var max_re: float = 1.0;
- var min_im: float = -1.2;
- var max_im: float = 1.2;
+ let min_re: float = -2.2;
+ let max_re: float = 1.0;
+ let min_im: float = -1.2;
+ let max_im: float = 1.2;
for y in 0..height {
- var im: float =
+ let im: float =
max_im - (max_im - min_im) * ( ((float)y) / ((float)(height - 1)) );
for x in 0..width {
- var re: float =
+ let re: float =
min_re + (max_re - min_re) * ( ((float)x) / ((float)(width - 1)) );
- var c: Complex = complex_make(re, im);
- var z: Complex = complex_make(0.0, 0.0);
+ let c: Complex = complex_make(re, im);
+ let z: Complex = complex_make(0.0, 0.0);
- var iter: int = 0;
+ let iter: int = 0;
while (iter < max_iter and complex_abs2(z) <= 4.0) {
z = complex_add(complex_mul(z, z), c);
iter += 1;
}
- var pixel = pick_char(iter, max_iter, edge_chars, edge_count);
+ let pixel = pick_char(iter, max_iter, edge_chars, edge_count);
print "{pixel}";
}
print "\n";
diff --git a/examples/graphics/raylib_demo.zc b/examples/graphics/raylib_demo.zc
index 77b661e..f0e4f57 100644
--- a/examples/graphics/raylib_demo.zc
+++ b/examples/graphics/raylib_demo.zc
@@ -8,11 +8,11 @@ fn main() {
raylib::SetTargetFPS(60);
- var x = 400;
- var y = 300;
- var dx = 5;
- var dy = 4;
- var radius = 30;
+ let x = 400;
+ let y = 300;
+ let dx = 5;
+ let dy = 4;
+ let radius = 30;
while !raylib::WindowShouldClose()
{
diff --git a/examples/networking/echo_server.zc b/examples/networking/echo_server.zc
index 1cecb74..072c3a2 100644
--- a/examples/networking/echo_server.zc
+++ b/examples/networking/echo_server.zc
@@ -4,27 +4,27 @@ import "std/net.zc"
fn main() {
"Starting Echo Server on 127.0.0.1:8080...";
- var listener_res = TcpListener::bind("127.0.0.1", 8080);
+ let listener_res = TcpListener::bind("127.0.0.1", 8080);
if listener_res.is_err() {
!"Failed to bind: {listener_res.err}";
return 1;
}
- var listener = listener_res.unwrap();
+ let listener = listener_res.unwrap();
defer listener.close();
loop {
- var client_res = listener.accept();
+ let client_res = listener.accept();
if client_res.is_ok() {
- var stream = client_res.unwrap();
+ let stream = client_res.unwrap();
defer stream.close();
- var buf: char[1024];
+ let buf: char[1024];
- var read_res = stream.read(buf, 1024);
+ let read_res = stream.read(buf, 1024);
if read_res.is_ok() {
- var bytes = read_res.unwrap();
+ let bytes = read_res.unwrap();
if bytes > 0 {
stream.write(buf, bytes);
"Echoed {bytes} bytes.";
diff --git a/examples/process/env.zc b/examples/process/env.zc
index 1506229..0ea7437 100644
--- a/examples/process/env.zc
+++ b/examples/process/env.zc
@@ -4,11 +4,11 @@ import "std/env.zc"
fn main() -> int {
// ----
- // get: Retrieves the env-var as borrowed string (char *) (no alloc)
+ // get: Retrieves the env-let as borrowed string (char *) (no alloc)
// ---
// @Example usage: On Linux (and some variants) PATH is already defined.
// ---
- var path = Env::get("PATH");
+ let path = Env::get("PATH");
if (path.is_some()) {
println "PATH is: {path.unwrap()}";
@@ -17,18 +17,18 @@ fn main() -> int {
}
// ----
- // set: Sets an env-var variable
- // get_dup: Retrieves the env-var as caller-owned String() (heap alloc)
+ // set: Sets an env-let variable
+ // get_dup: Retrieves the env-let as caller-owned String() (heap alloc)
// ---
// @Example usage: In your terminal type "export HELLO=world" or use Env::set()
// ---
- var res = Env::set("HELLO", "world");
+ let res = Env::set("HELLO", "world");
//=> check res against EnvRes::OK()
- var hello = Env::get_dup("HELLO");
+ let hello = Env::get_dup("HELLO");
if (hello.is_some()) {
- var hello_str = hello.unwrap();
+ let hello_str = hello.unwrap();
defer hello_str.free();
println "HELLO is: {hello_str.c_str()}";
@@ -37,11 +37,11 @@ fn main() -> int {
}
// ----
- // unset: Unsets an existing env-var
+ // unset: Unsets an existing env-let
// ---
Env::unset("HELLO");
- var hello_now2 = Env::get("HELLO");
+ let hello_now2 = Env::get("HELLO");
if (hello_now2.is_none()) {
println "HELLO is now unset";
diff --git a/examples/scripting/lua/lua.zc b/examples/scripting/lua/lua.zc
index 74403bb..a8463fa 100644
--- a/examples/scripting/lua/lua.zc
+++ b/examples/scripting/lua/lua.zc
@@ -14,7 +14,7 @@ fn l_zenc_hello(L: lua_State*) -> int {
}
fn main() {
- var L: lua_State* = luaL_newstate();
+ let L: lua_State* = luaL_newstate();
if (!L) return !"Could not initialize LUA.";
diff --git a/examples/tools/mini_grep.zc b/examples/tools/mini_grep.zc
index 827b73a..39fec07 100644
--- a/examples/tools/mini_grep.zc
+++ b/examples/tools/mini_grep.zc
@@ -21,22 +21,22 @@ fn str_find_case(haystack: string, needle: string, ignore_case: bool) -> Option<
{
if (!ignore_case)
{
- var res = (string)strstr(haystack, needle);
+ let res = (string)strstr(haystack, needle);
if (res != NULL) return Option<string>::Some(res);
return Option<string>::None();
}
- var h = haystack;
- var n = needle;
- var n_len = strlen(needle);
+ let h = haystack;
+ let n = needle;
+ let n_len = strlen(needle);
while (*h != 0)
{
- var is_match: bool = true;
+ let is_match: bool = true;
for i in 0..n_len
{
- var hc = to_lower(*(h + i));
- var nc = to_lower(*(n + i));
+ let hc = to_lower(*(h + i));
+ let nc = to_lower(*(n + i));
if (hc != nc)
{
is_match = false;
@@ -59,7 +59,7 @@ fn print_highlight(line: string, match_ptr: string, match_len: usize, config: Gr
return;
}
- var current = line;
+ let current = line;
while (current < match_ptr)
{
"{*current}"..;
@@ -85,15 +85,15 @@ fn print_highlight(line: string, match_ptr: string, match_len: usize, config: Gr
}
fn grep_file(path: string, config: GrepConfig) -> Result<int> {
- var content_str: String = File::read_all(path)?;
+ let content_str: String = File::read_all(path)?;
defer content_str.destroy();
- var content = content_str.c_str();
+ let content = content_str.c_str();
- var line_num = 1;
- var ptr = content;
- var line_start = content;
+ let line_num = 1;
+ let ptr = content;
+ let line_start = content;
- var q_len = strlen(config.query);
+ let q_len = strlen(config.query);
while (*ptr != 0)
{
@@ -101,8 +101,8 @@ fn grep_file(path: string, config: GrepConfig) -> Result<int> {
{
*ptr = 0;
- var match_opt = str_find_case(line_start, config.query, config.ignore_case);
- var found_str = "";
+ let match_opt = str_find_case(line_start, config.query, config.ignore_case);
+ let found_str = "";
if (match_opt.is_some()) found_str = match_opt.unwrap();
if ((match_opt.is_some() and !config.invert) || (!match_opt.is_some() and config.invert))
@@ -142,8 +142,8 @@ fn grep_file(path: string, config: GrepConfig) -> Result<int> {
if (ptr > line_start)
{
- var match_opt = str_find_case(line_start, config.query, config.ignore_case);
- var found_str = "";
+ let match_opt = str_find_case(line_start, config.query, config.ignore_case);
+ let found_str = "";
if (match_opt.is_some()) found_str = match_opt.unwrap();
if ((match_opt.is_some() and !config.invert) || (!match_opt.is_some() and config.invert))
@@ -164,17 +164,17 @@ fn grep_file(path: string, config: GrepConfig) -> Result<int> {
}
fn visit_dir(path: string, config: GrepConfig) {
- var entries_res = File::read_dir(path);
+ let entries_res = File::read_dir(path);
guard entries_res.is_ok() else return;
- var entries = entries_res.unwrap();
- var p_base = Path::new(path);
+ let entries = entries_res.unwrap();
+ let p_base = Path::new(path);
for i in 0..entries.length()
{
- var entry: DirEntry = entries.get(i);
- var full_path_obj = p_base.join(entry.name.c_str());
- var full_path = full_path_obj.c_str();
+ let entry: DirEntry = entries.get(i);
+ let full_path_obj = p_base.join(entry.name.c_str());
+ let full_path = full_path_obj.c_str();
if (entry.is_dir)
{
@@ -209,7 +209,7 @@ fn main(argc: int, argv: string*)
return 0;
}
- var config = GrepConfig {
+ let config = GrepConfig {
query: NULL,
path: NULL,
ignore_case: false,
@@ -219,10 +219,10 @@ fn main(argc: int, argv: string*)
color: false
};
- var arg_idx = 1;
+ let arg_idx = 1;
while (arg_idx < argc)
{
- var arg = argv[arg_idx];
+ let arg = argv[arg_idx];
if (arg[0] == '-')
{
if (arg[1] == '-')
@@ -240,10 +240,10 @@ fn main(argc: int, argv: string*)
}
else
{
- var len = strlen(arg);
+ let len = strlen(arg);
for i in 1..len
{
- var c = arg[i];
+ let c = arg[i];
match c {
'i' => config.ignore_case = true,
'n' => config.line_numbers = true,
@@ -275,13 +275,13 @@ fn main(argc: int, argv: string*)
if (File::exists(config.path))
{
- var meta_res = File::metadata(config.path);
+ let meta_res = File::metadata(config.path);
if (meta_res.is_err())
{
!"grep: {config.path}: Error reading metadata";
return 1;
}
- var meta = meta_res.unwrap();
+ let meta = meta_res.unwrap();
if (meta.is_dir)
{
@@ -296,7 +296,7 @@ fn main(argc: int, argv: string*)
}
else
{
- var res = grep_file(config.path, config);
+ let res = grep_file(config.path, config);
if (res.is_err()) {
!"Error: {res.err}";
return 1;