add core.capture_output

This commit is contained in:
MihailRis
2025-03-13 22:05:14 +03:00
parent ffac010e54
commit 1bb25e99c6
4 changed files with 37 additions and 3 deletions
+28
View File
@@ -273,6 +273,33 @@ static int l_blank(lua::State*) {
return 0;
}
static int l_capture_output(lua::State* L) {
int argc = lua::gettop(L) - 1;
if (!lua::isfunction(L, 1)) {
throw std::runtime_error("function expected as argument 1");
}
for (int i = 0; i < argc; i++) {
lua::pushvalue(L, i + 2);
}
lua::pushvalue(L, 1);
auto prev_output = output_stream;
auto prev_error = error_stream;
std::stringstream captured_output;
output_stream = &captured_output;
error_stream = &captured_output;
lua::call_nothrow(L, argc, 0);
output_stream = prev_output;
error_stream = prev_error;
lua::pushstring(L, captured_output.str());
return 1;
}
const luaL_Reg corelib[] = {
{"blank", lua::wrap<l_blank>},
{"get_version", lua::wrap<l_get_version>},
@@ -292,6 +319,7 @@ const luaL_Reg corelib[] = {
{"get_setting_info", lua::wrap<l_get_setting_info>},
{"open_folder", lua::wrap<l_open_folder>},
{"quit", lua::wrap<l_quit>},
{"capture_output", lua::wrap<l_capture_output>},
{"__load_texture", lua::wrap<l_load_texture>},
{NULL, NULL}
};