Skip to content

Instantly share code, notes, and snippets.

@giulioz
Created August 15, 2019 17:27
Show Gist options
  • Save giulioz/51d4eee40f6ddbd6964e8185cbdd924a to your computer and use it in GitHub Desktop.
Save giulioz/51d4eee40f6ddbd6964e8185cbdd924a to your computer and use it in GitHub Desktop.
Tiny Smalltalk-like objects in C.
#include <stdio.h>
#include <stdlib.h>
typedef struct Object Object;
typedef struct MethodChain {
const char* selector;
Object* (*handler)(Object* self);
struct MethodChain* next;
} MethodChain;
struct Object {
MethodChain* methods;
};
Object* msg_send(Object* self, const char* selector) {
if (!self) {
printf("Error sending message %s.\n", selector);
}
MethodChain* currentMethod = self->methods;
while (currentMethod && currentMethod->selector != selector) {
currentMethod = currentMethod->next;
}
if (currentMethod && currentMethod->selector == selector) {
return currentMethod->handler(self);
} else {
printf("Error sending message %s.\n", selector);
return NULL;
}
}
Object* greet(Object* self) {
printf("Hello world!\n");
return NULL;
}
int main() {
const char* greetSelector = "greet";
MethodChain transcriptMethodCheer = {0};
transcriptMethodCheer.handler = greet;
transcriptMethodCheer.selector = greetSelector;
Object transcript = {0};
transcript.methods = &transcriptMethodCheer;
Object* Transcript = &transcript;
msg_send(Transcript, greetSelector);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment