diff --git a/src/cbaselib.c b/src/cbaselib.c index 7776836..0b6bc01 100644 --- a/src/cbaselib.c +++ b/src/cbaselib.c @@ -110,6 +110,22 @@ int cosmoB_loadstring(CState *state, int nargs, CValue *args) { return 2; // , or } +int cosmoB_error(CState *state, int nargs, CValue *args) { + if (nargs < 1) { + cosmoV_error(state, "error() expected 1 argument, got %d!", nargs); + return 0; + } + + if (!IS_STRING(args[0])) { + cosmoV_typeError(state, "error()", "", "%s", cosmoV_typeStr(args[0])); + return 0; + } + + cosmoV_error(state, "%s", cosmoV_readCString(args[0])); + + return 0; +} + void cosmoB_loadLibrary(CState *state) { const char *identifiers[] = { "print", @@ -118,7 +134,8 @@ void cosmoB_loadLibrary(CState *state) { "pcall", "tonumber", "tostring", - "loadstring" + "loadstring", + "error" }; CosmoCFunction baseLib[] = { @@ -128,7 +145,8 @@ void cosmoB_loadLibrary(CState *state) { cosmoB_pcall, cosmoB_tonumber, cosmoB_tostring, - cosmoB_loadstring + cosmoB_loadstring, + cosmoB_error }; int i; @@ -492,13 +510,30 @@ int cosmoB_sChar(CState *state, int nargs, CValue *args) { return 1; } +int cosmoB_sLen(CState *state, int nargs, CValue *args) { + if (nargs < 1) { + cosmoV_error(state, "string.len() expected 1 argument, got %d", nargs); + return 0; + } + + if (!IS_STRING(args[0])) { + cosmoV_typeError(state, "string.len", "", "%s", cosmoV_typeStr(args[0])); + return 0; + } + + cosmoV_pushNumber(state, strlen(cosmoV_readCString(args[0]))); + + return 1; +} + void cosmoB_loadStrLib(CState *state) { const char *identifiers[] = { "sub", "find", "split", "byte", - "char" + "char", + "len" }; CosmoCFunction strLib[] = { @@ -506,7 +541,8 @@ void cosmoB_loadStrLib(CState *state) { cosmoB_sFind, cosmoB_sSplit, cosmoB_sByte, - cosmoB_sChar + cosmoB_sChar, + cosmoB_sLen }; // make string library object diff --git a/src/cobj.h b/src/cobj.h index 6a77a6f..b5fde5f 100644 --- a/src/cobj.h +++ b/src/cobj.h @@ -120,6 +120,7 @@ typedef struct CObjUpval { #define IS_CLOSURE(x) isObjType(x, COBJ_CLOSURE) #define cosmoV_readString(x) ((CObjString*)cosmoV_readRef(x)) +#define cosmoV_readCString(x) (((CObjString*)cosmoV_readRef(x))->str) #define cosmoV_readObject(x) ((CObjObject*)cosmoV_readRef(x)) #define cosmoV_readTable(x) ((CObjTable*)cosmoV_readRef(x)) #define cosmoV_readFunction(x) ((CObjFunction*)cosmoV_readRef(x))