mirror of
https://github.com/krgamestudios/Toy.git
synced 2026-04-20 01:04:08 +10:00
Implemented native C functions called from Toy scripts
There's only example functions for now, but I'll add type-specific functions later.
This commit is contained in:
@@ -7,6 +7,8 @@
|
||||
#include "toy_compiler.h"
|
||||
#include "toy_vm.h"
|
||||
|
||||
#include "standard_library.h"
|
||||
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
@@ -337,6 +339,12 @@ int repl(const char* filepath, bool verbose) {
|
||||
Toy_VM vm;
|
||||
Toy_initVM(&vm);
|
||||
|
||||
//hacky test
|
||||
if (vm.scope == NULL) {
|
||||
vm.scope = Toy_pushScope(&vm.memoryBucket, NULL);
|
||||
initStandardLibrary(&vm);
|
||||
}
|
||||
|
||||
printf("%s> ", prompt); //shows the terminal prompt and begin
|
||||
|
||||
//read from the terminal
|
||||
|
||||
53
repl/standard_library.c
Normal file
53
repl/standard_library.c
Normal file
@@ -0,0 +1,53 @@
|
||||
#include "standard_library.h"
|
||||
#include "toy_console_colors.h"
|
||||
|
||||
#include "toy_print.h"
|
||||
#include "toy_scope.h"
|
||||
#include "toy_stack.h"
|
||||
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
|
||||
typedef struct CallbackPairs {
|
||||
const char* name;
|
||||
Toy_nativeCallback callback;
|
||||
} CallbackPairs;
|
||||
|
||||
//example callbacks
|
||||
void hello(Toy_VM* vm) {
|
||||
(void)vm;
|
||||
Toy_print("Hello world!");
|
||||
}
|
||||
|
||||
void debug(Toy_VM* vm) {
|
||||
(void)vm;
|
||||
Toy_print("This function returns the integer '42' to the calling scope.");
|
||||
Toy_pushStack(&vm->stack, TOY_VALUE_FROM_INTEGER(42));
|
||||
}
|
||||
|
||||
CallbackPairs callbackPairs[] = {
|
||||
{"hello", hello},
|
||||
{"debug", debug},
|
||||
{NULL, NULL},
|
||||
};
|
||||
|
||||
//exposed functions
|
||||
void initStandardLibrary(Toy_VM* vm) {
|
||||
if (vm == NULL || vm->scope == NULL || vm->memoryBucket == NULL) {
|
||||
fprintf(stderr, TOY_CC_ERROR "ERROR: Can't initialize standard library, exiting\n" TOY_CC_RESET);
|
||||
exit(-1);
|
||||
}
|
||||
|
||||
//declare each pair
|
||||
for (int i = 0; callbackPairs[i].name; i++) {
|
||||
//cheat
|
||||
Toy_String key = (Toy_String){
|
||||
.leaf = { ._padding = { .type = TOY_STRING_LEAF, .length = strlen(callbackPairs[i].name), .refCount = 1, .cachedHash = 0 }, .data = callbackPairs[i].name }
|
||||
};
|
||||
|
||||
Toy_Function* fn = Toy_createFunctionFromCallback(&(vm->memoryBucket), callbackPairs[i].callback);
|
||||
|
||||
Toy_declareScope(vm->scope, &key, TOY_VALUE_FUNCTION, TOY_VALUE_FROM_FUNCTION(fn), true);
|
||||
}
|
||||
}
|
||||
5
repl/standard_library.h
Normal file
5
repl/standard_library.h
Normal file
@@ -0,0 +1,5 @@
|
||||
#pragma once
|
||||
|
||||
#include "toy_vm.h"
|
||||
|
||||
void initStandardLibrary(Toy_VM*);
|
||||
Reference in New Issue
Block a user