Files
dl_old/dl/script/dl_squirrel.cpp
T
2023-08-19 21:58:28 +08:00

119 lines
2.3 KiB
C++
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
#include "dl_squirrel.h"
#include <cstdarg>
#include <cstdio>
#include <squirrel.h>
#include "io/dl_log.h"
namespace dl
{
class SquirrelImp
{
friend class Squirrel;
private:
HSQUIRRELVM _v;
static void _callback_compile_error(HSQUIRRELVM,
const SQChar* desc, const SQChar* source, SQInteger line, SQInteger column)
{
log_err("Squirrel: {},{}:{}-{}", desc, source, line, column);
}
};
Squirrel* g_squirrel;
void SQ_print(HSQUIRRELVM v, const SQChar* format, ...)
{
va_list args;
int len;
va_start(args, format);
len = vsnprintf(nullptr, 0, format, args) + 1;
va_end(args);
std::string ret;
ret.resize(len);
va_start(args, format);
vsnprintf((char*)ret.data(), len, format, args);
va_end(args);
ret.pop_back();
log_info0(ret);
}
void SQ_print_error(HSQUIRRELVM v, const SQChar* format, ...)
{
va_list args;
int len;
va_start(args, format);
len = vsnprintf(nullptr, 0, format, args) + 1;
va_end(args);
std::string ret;
ret.resize(len);
va_start(args, format);
vsnprintf((char*)ret.data(), len, format, args);
va_end(args);
ret.pop_back();
log_err0(ret);
}
Squirrel::Squirrel()
{
_imp = new SquirrelImp;
_imp->_v = sq_open(1024); //creates a VM with initial stack size 1024
HSQUIRRELVM v = _imp->_v;
//sq_seterrorhandler(_imp->_v);
// 设置编译失败回调
sq_setcompilererrorhandler(v, SquirrelImp::_callback_compile_error);
sq_enabledebuginfo(v, true);
// 设置打印函数
sq_setprintfunc(v, SQ_print, SQ_print_error);
//sq_pushroottable(v);
//sq_pushstring(v, "log", -1);
//sq_newclosure(v, print_str, 0); //create a new function
//sq_newslot(v, -3, SQFalse);
//sq_pop(v, 1); //pops the root table
}
Squirrel::~Squirrel()
{
sq_close(_imp->_v);
delete _imp;
}
void Squirrel::Compile(BufferView buf)
{
if (SQ_FAILED(sq_compilebuffer(_imp->_v, (SQChar*)buf.data(), buf.size(), "xx", true)))
return;
if (SQ_FAILED(sq_call(_imp->_v, 1, false, true)))
return;
}
void Squirrel::Call()
{
auto fn = [](HSQUIRRELVM v) {
sq_pushroottable(v);
sq_pushstring(v, "print", -1);
sq_get(v, -2); //get the function from the root table
sq_pushroottable(v); //'this' (function environment object)
sq_pushstring(v, "three", -1);
sq_call(v, 2, SQFalse, SQTrue);
sq_pop(v, 2); //pops the roottable and the function
};
fn(_imp->_v);
}
}