cosmoV_register now uses the stack to pass params

This commit is contained in:
2020-12-19 21:15:12 -06:00
parent f6aaeb3417
commit de3a89ad4f
5 changed files with 23 additions and 53 deletions

View File

@@ -5,10 +5,9 @@
#include "cmem.h"
void cosmoB_loadLibrary(CState *state) {
cosmoM_freezeGC(state);
cosmoV_register(state, "print", cosmoV_newObj(cosmoO_newCFunction(state, cosmoB_print)));
cosmoV_register(state, "foreach", cosmoV_newObj(cosmoO_newCFunction(state, cosmoB_foreach)));
cosmoM_unfreezeGC(state);
cosmoV_pushString(state, "print");
cosmoV_pushCFunction(state, cosmoB_print);
cosmoV_register(state, 1); // sets "print" global to cosmoB_print
}
int cosmoB_print(CState *state, int nargs, CValue *args) {
@@ -21,40 +20,6 @@ int cosmoB_print(CState *state, int nargs, CValue *args) {
return 0; // print doesn't return any args
}
int cosmoB_foreach(CState *state, int nargs, CValue *args) {
if (nargs != 2) {
cosmoV_error(state, "foreach() expected 2 parameters, got %d!", nargs);
return 0;
}
if (!IS_DICT(args[0])) {
cosmoV_error(state, "foreach() expected first parameter to be <dictionary>, got %s!", cosmoV_typeStr(args[0]));
return 0;
}
if (!IS_CALLABLE(args[1])) {
cosmoV_error(state, "foreach() expected second parameter to be callable, got %s!", cosmoV_typeStr(args[1]));
return 0;
}
// loop through dictionary table, calling args[1] on active entries
CObjDict *dict = (CObjDict*)cosmoV_readObj(args[0]);
for (int i = 0; i < dict->tbl.capacity; i++) {
CTableEntry *entry = &dict->tbl.table[i];
if (!IS_NIL(entry->key)) {
// push key & value, then call args[1]
cosmoV_pushValue(state, args[1]);
cosmoV_pushValue(state, entry->key);
cosmoV_pushValue(state, entry->val);
cosmoV_call(state, 2, 0);
}
}
return 0;
}
int cosmoB_dsetProto(CState *state, int nargs, CValue *args) {
if (nargs == 2) {
CObjObject *obj = cosmoV_readObject(args[0]); // object to set proto too