forked from nulang-org/nulang
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathchat_room.nula
More file actions
57 lines (44 loc) · 1.27 KB
/
Copy pathchat_room.nula
File metadata and controls
57 lines (44 loc) · 1.27 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
// Chat Room — multi-actor messaging with the actor name registry.
// Actors register under names, discover each other via `Actor.whereis`,
// and exchange messages. Demonstrates BEAM-style registry primitives.
//
// Run with: nulang examples/chat_room.nula
actor ChatRoom {
state messages: Int = 0
behavior broadcast(sender_name: String, text: String) {
self.messages = self.messages + 1
perform IO.print("[" + sender_name + "]: " + text)
}
behavior count() {
perform IO.print(
"Total messages: " + perform Int.to_string(self.messages)
)
}
}
actor ChatClient {
state room_ref: Int = 0
behavior init(room: Int) {
self.room_ref = room
}
behavior say(name: String, text: String) {
self.room_ref ! broadcast(name, text)
}
behavior leave(name: String) {
perform IO.print(name + " left the room")
}
}
fn main() {
// Create the room
let room = spawn ChatRoom {}
// Two clients join and chat
let alice = spawn ChatClient {}
let bob = spawn ChatClient {}
alice ! init(room)
bob ! init(room)
alice ! say("alice", "Hello everyone!")
bob ! say("bob", "Hi Alice!")
room ! count()
alice ! leave("alice")
bob ! leave("bob")
0
}