From a14e6a908059025c99ae83e079e73e62c9e4b113 Mon Sep 17 00:00:00 2001 From: xx Date: Fri, 7 Mar 2025 21:14:52 +0800 Subject: [PATCH] =?UTF-8?q?=E5=A2=9E=E5=8A=A0=E8=BD=ACINT=E7=9A=84?= =?UTF-8?q?=E6=96=B9=E6=B3=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/module/globalfuns.cpp | 25 +++++++++++++++++++++++++ src/module/globalfuns.h | 6 ++++++ 2 files changed, 31 insertions(+) diff --git a/src/module/globalfuns.cpp b/src/module/globalfuns.cpp index be95a71..459864c 100644 --- a/src/module/globalfuns.cpp +++ b/src/module/globalfuns.cpp @@ -59,6 +59,31 @@ void module::globalfuncs::create_env(const std::string& lua_filepath,sol::this_s t.detach(); } +std::optional module::globalfuncs::toint(const sol::object& obj) +{ + sol::type t = obj.get_type(); + switch (t) { + case sol::type::number: + // 直接将数字转换为 int + return obj.as(); + case sol::type::string: { + // 尝试将字符串转换为 int + std::string s = obj.as(); + try { + return std::stoi(s); + } + catch (const std::exception&) { + return std::nullopt; + } + } + case sol::type::boolean: + // 布尔值 true 转为 1, false 转为 0 + return obj.as() ? 1 : 0; + default: + // 其它类型返回空 + return std::nullopt; + } +} void module::globalfuncs::regist(sol::state* lua) { lua->set_function("fw_set_ptr", module::globalfuncs::set_ptr); diff --git a/src/module/globalfuns.h b/src/module/globalfuns.h index 0741783..186dc7a 100644 --- a/src/module/globalfuns.h +++ b/src/module/globalfuns.h @@ -53,6 +53,12 @@ namespace module /// /// static void create_env(const std::string& lua_filepath,sol::this_state ts); + /// + /// 转INT + /// + /// + static std::optional toint(const sol::object& arg); + static void regist(sol::state* lua); };