Added error, string.len, and cosmoV_readCString

Commit authored by https://github.com/NeoInversion
This commit is contained in:
CPunch 2021-02-11 00:27:23 -06:00 committed by GitHub
commit 43a278e12d
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 41 additions and 4 deletions

View File

@ -110,6 +110,22 @@ int cosmoB_loadstring(CState *state, int nargs, CValue *args) {
return 2; // <boolean>, <closure> or <error>
}
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()", "<string>", "%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", "<string>", "%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

View File

@ -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))