From ae43ad6e1703ebdc82906898e25f736c2b1a86e4 Mon Sep 17 00:00:00 2001 From: actboy168 Date: Sat, 20 Jan 2024 19:59:24 +0800 Subject: [PATCH] add isatty/write_console --- binding/port/lua_windows.cpp | 56 +++++++++++++++++++++++++++++------- 1 file changed, 45 insertions(+), 11 deletions(-) diff --git a/binding/port/lua_windows.cpp b/binding/port/lua_windows.cpp index 2c44220b..d4fd9696 100644 --- a/binding/port/lua_windows.cpp +++ b/binding/port/lua_windows.cpp @@ -1,3 +1,4 @@ +#include #include #include #include @@ -21,19 +22,50 @@ namespace bee::lua_windows { static int filemode(lua_State* L) { luaL_Stream* p = lua::tofile(L, 1); auto mode = lua::checkstrview(L, 2); - if (p && p->closef && p->f) { - int ok = _setmode(_fileno(p->f), mode[0] == 'b' ? _O_BINARY : _O_TEXT); - if (ok == -1) { - lua_pushnil(L); - lua_pushstring(L, make_crterror("_setmode").c_str()); - return 2; - } - lua_pushboolean(L, 1); + if (!p || !p->closef || !p->f) { + lua_pushnil(L); + lua_pushstring(L, make_error(std::make_error_code(std::errc::bad_file_descriptor), "filemode").c_str()); + return 2; + } + int ok = _setmode(_fileno(p->f), mode[0] == 'b' ? _O_BINARY : _O_TEXT); + if (ok == -1) { + lua_pushnil(L); + lua_pushstring(L, make_crterror("filemode").c_str()); + return 2; + } + lua_pushboolean(L, 1); + return 1; + } + + static int isatty(lua_State* L) { + luaL_Stream* p = lua::tofile(L, 1); + if (!p || !p->closef || !p->f) { + lua_pushboolean(L, 0); return 1; } - lua_pushnil(L); - lua_pushstring(L, make_error(std::make_error_code(std::errc::bad_file_descriptor), "_setmode").c_str()); - return 2; + HANDLE handle = (HANDLE)_get_osfhandle(_fileno(p->f)); + lua_pushboolean(L, FILE_TYPE_CHAR == GetFileType(handle)); + return 1; + } + + static int write_console(lua_State* L) { + luaL_Stream* p = lua::tofile(L, 1); + auto msg = win::u2w(lua::checkstrview(L, 2)); + if (!p || !p->closef || !p->f) { + lua_pushnil(L); + lua_pushstring(L, make_error(std::make_error_code(std::errc::bad_file_descriptor), "write_console").c_str()); + return 2; + } + HANDLE handle = (HANDLE)_get_osfhandle(_fileno(p->f)); + DWORD written = 0; + BOOL ok = WriteConsoleW(handle, (void*)msg.c_str(), (DWORD)msg.size(), &written, NULL); + if (!ok) { + lua_pushnil(L); + lua_pushstring(L, make_syserror("write_console").c_str()); + return 2; + } + lua_pushinteger(L, written); + return 1; } static int luaopen(lua_State* L) { @@ -41,6 +73,8 @@ namespace bee::lua_windows { { "u2a", lu2a }, { "a2u", la2u }, { "filemode", filemode }, + { "isatty", isatty }, + { "write_console", write_console }, { NULL, NULL } }; luaL_newlibtable(L, lib);