src/squirrel_std.cpp
branchnoai
changeset 9577 8e93be390b45
parent 9487 0575126e0267
child 9578 2e05c1b002f0
--- a/src/squirrel_std.cpp	Wed Apr 11 16:48:42 2007 +0000
+++ b/src/squirrel_std.cpp	Wed Apr 11 19:53:33 2007 +0000
@@ -1,6 +1,8 @@
 
 #include <squirrel.h>
+#include <sqstdio.h>
 #include "stdafx.h"
+#include "debug.h"
 #include "squirrel.hpp"
 #include "squirrel_std.hpp"
 #include "helpers.hpp"
@@ -17,6 +19,52 @@
 	return 1;
 }
 
+SQInteger SquirrelStd::require(HSQUIRRELVM vm)
+{
+	SQInteger top = sq_gettop(vm);
+	const SQChar *filename;
+	SQChar *real_filename;
+
+	sq_getstring(vm, 2, &filename);
+
+	/* Get the script-name of the current file, so we can work relative from it */
+	SQStackInfos si;
+	sq_stackinfos(vm, 1, &si);
+	if (si.source == NULL) {
+		DEBUG(misc, 0, "[squirrel] Couldn't detect the script-name of the 'require'-caller; this should never happen!");
+		return SQ_ERROR;
+	}
+	real_filename = strdup(si.source);
+	/* Keep the dir, remove the rest */
+	SQChar *s = strrchr(real_filename, PATHSEPCHAR);
+	if (s != NULL) {
+		/* Keep the PATHSEPCHAR there, remove the rest */
+		*s++;
+		*s = '\0';
+	}
+	/* And now we concat, so we are relative from the current script */
+	strcat(real_filename, filename);
+
+	/* Make sure we are in the root-table, so everything is included in the root-level */
+	sq_pushroottable(vm);
+	/* Compile and load the file */
+	if (!SQ_SUCCEEDED(sqstd_dofile(vm, real_filename, SQFalse, SQTrue))) {
+		DEBUG(misc, 0, "[squirrel] Failed to compile '%s'", filename);
+		sq_settop(vm, top);
+		return SQ_ERROR;
+	}
+	/* Reset the top, so the stack stays correct */
+	sq_settop(vm, top);
+	return 0;
+}
+
+void squirrel_register_global_std(Squirrel *engine)
+{
+	/* We don't use squirrel_helper here, as we want to register to the global
+	 *  scope and not to a class. */
+	engine->AddMethod("require", &SquirrelStd::require, 2, "?s");
+}
+
 void squirrel_register_std(Squirrel *engine)
 {
 	/* We don't use squirrel_helper here, as we want to register to the global