Created
August 15, 2019 17:27
-
-
Save giulioz/51d4eee40f6ddbd6964e8185cbdd924a to your computer and use it in GitHub Desktop.
Tiny Smalltalk-like objects in C.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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