4 * This file is part of OpenTTD.
5 * OpenTTD is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, version 2.
6 * OpenTTD is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
7 * See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with OpenTTD. If not, see <http://www.gnu.org/licenses/>.
10 /** @file squirrel_std.cpp Implements the Squirrel Standard Function class */
12 #include "../stdafx.h"
14 #include <sqstdmath.h>
16 #include "squirrel_std.hpp"
17 #include "../core/alloc_func.hpp"
18 #include "../core/math_func.hpp"
19 #include "../string_func.h"
21 #include "../safeguards.h"
24 SQInteger
SquirrelStd::min(HSQUIRRELVM vm
)
28 sq_getinteger(vm
, 2, &tmp1
);
29 sq_getinteger(vm
, 3, &tmp2
);
30 sq_pushinteger(vm
, ::min(tmp1
, tmp2
));
34 SQInteger
SquirrelStd::max(HSQUIRRELVM vm
)
38 sq_getinteger(vm
, 2, &tmp1
);
39 sq_getinteger(vm
, 3, &tmp2
);
40 sq_pushinteger(vm
, ::max(tmp1
, tmp2
));
44 SQInteger
SquirrelStd::require(HSQUIRRELVM vm
)
46 SQInteger top
= sq_gettop(vm
);
47 const SQChar
*filename
;
49 sq_getstring(vm
, 2, &filename
);
51 /* Get the script-name of the current file, so we can work relative from it */
53 sq_stackinfos(vm
, 1, &si
);
54 if (si
.source
== NULL
) {
55 DEBUG(misc
, 0, "[squirrel] Couldn't detect the script-name of the 'require'-caller; this should never happen!");
60 strecpy(path
, si
.source
, lastof(path
));
61 /* Keep the dir, remove the rest */
62 SQChar
*s
= strrchr(path
, PATHSEPCHAR
);
64 /* Keep the PATHSEPCHAR there, remove the rest */
68 strecat(path
, filename
, lastof(path
));
69 #if (PATHSEPCHAR != '/')
70 for (char *n
= path
; *n
!= '\0'; n
++) if (*n
== '/') *n
= PATHSEPCHAR
;
73 Squirrel
*engine
= (Squirrel
*)sq_getforeignptr(vm
);
74 bool ret
= engine
->LoadScript(vm
, path
);
76 /* Reset the top, so the stack stays correct */
79 return ret
? 0 : SQ_ERROR
;
82 SQInteger
SquirrelStd::notifyallexceptions(HSQUIRRELVM vm
)
86 if (sq_gettop(vm
) >= 1) {
87 if (SQ_SUCCEEDED(sq_getbool(vm
, -1, &b
))) {
88 sq_notifyallexceptions(vm
, b
);
96 void squirrel_register_global_std(Squirrel
*engine
)
98 /* We don't use squirrel_helper here, as we want to register to the global
99 * scope and not to a class. */
100 engine
->AddMethod("require", &SquirrelStd::require
, 2, ".s");
101 engine
->AddMethod("notifyallexceptions", &SquirrelStd::notifyallexceptions
, 2, ".b");
104 void squirrel_register_std(Squirrel
*engine
)
106 /* We don't use squirrel_helper here, as we want to register to the global
107 * scope and not to a class. */
108 engine
->AddMethod("min", &SquirrelStd::min
, 3, ".ii");
109 engine
->AddMethod("max", &SquirrelStd::max
, 3, ".ii");
111 sqstd_register_mathlib(engine
->GetVM());