🎨 open return nil if fails

This commit is contained in:
ValKmjolnir 2025-02-15 14:24:08 +08:00
parent b177a58662
commit 065f6ae162
2 changed files with 11 additions and 7 deletions

View File

@ -380,8 +380,11 @@ var builtin_substr(context* ctx, gc* ngc) {
} }
auto begin = static_cast<usize>(beg.num()); auto begin = static_cast<usize>(beg.num());
auto length = static_cast<usize>(len.num()); auto length = static_cast<usize>(len.num());
if (begin>=str.str().length()) { if (begin >= str.str().length()) {
return nas_err("native::susbtr", "begin index out of range: "+std::to_string(begin)); return nas_err(
"native::susbtr",
"begin index out of range: " + std::to_string(begin)
);
} }
return ngc->newstr(str.str().substr(begin, length)); return ngc->newstr(str.str().substr(begin, length));
} }
@ -406,7 +409,7 @@ var builtin_left(context* ctx, gc* ngc) {
if (!len.is_num()) { if (!len.is_num()) {
return nas_err("native::left", "\"length\" must be number"); return nas_err("native::left", "\"length\" must be number");
} }
if (len.num()<0) { if (len.num() < 0) {
return ngc->newstr(""); return ngc->newstr("");
} }
return ngc->newstr(str.str().substr(0, len.num())); return ngc->newstr(str.str().substr(0, len.num()));
@ -426,14 +429,14 @@ var builtin_right(context* ctx, gc* ngc) {
i32 length = static_cast<i32>(len.num()); i32 length = static_cast<i32>(len.num());
i32 srclen = static_cast<i32>(str.str().length()); i32 srclen = static_cast<i32>(str.str().length());
if (length>srclen) { if (length > srclen) {
length = srclen; length = srclen;
} }
if (length<0) { if (length < 0) {
length = 0; length = 0;
} }
return ngc->newstr(str.str().substr(srclen-length, srclen)); return ngc->newstr(str.str().substr(srclen - length, srclen));
} }
var builtin_cmp(context* ctx, gc* ngc) { var builtin_cmp(context* ctx, gc* ngc) {

View File

@ -59,8 +59,9 @@ var builtin_open(context* ctx, gc* ngc) {
return nas_err("io::open", "\"mode\" must be string"); return nas_err("io::open", "\"mode\" must be string");
} }
auto file_descriptor = fopen(name.str().c_str(), mode.str().c_str()); auto file_descriptor = fopen(name.str().c_str(), mode.str().c_str());
// if failed to open, just return nil for check
if (!file_descriptor) { if (!file_descriptor) {
return nas_err("io::open", "failed to open file <" + name.str() + ">"); return nil;
} }
var return_object = ngc->alloc(vm_type::vm_ghost); var return_object = ngc->alloc(vm_type::vm_ghost);
return_object.ghost().set( return_object.ghost().set(