Przeglądaj źródła

增加转INT的方法

xx 1 rok temu
rodzic
commit
76cdea2e13
2 zmienionych plików z 31 dodań i 0 usunięć
  1. 25 0
      src/module/globalfuns.cpp
  2. 6 0
      src/module/globalfuns.h

+ 25 - 0
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<int> module::globalfuncs::toint(const sol::object& obj)
+{
+	sol::type t = obj.get_type();
+	switch (t) {
+	case sol::type::number:
+		// 直接将数字转换为 int
+		return obj.as<int>();
+	case sol::type::string: {
+		// 尝试将字符串转换为 int
+		std::string s = obj.as<std::string>();
+		try {
+			return std::stoi(s);
+		}
+		catch (const std::exception&) {
+			return std::nullopt;
+		}
+	}
+	case sol::type::boolean:
+		// 布尔值 true 转为 1, false 转为 0
+		return obj.as<bool>() ? 1 : 0;
+	default:
+		// 其它类型返回空
+		return std::nullopt;
+	}
+}
 void module::globalfuncs::regist(sol::state* lua)
 {
 	lua->set_function("fw_set_ptr", module::globalfuncs::set_ptr);

+ 6 - 0
src/module/globalfuns.h

@@ -53,6 +53,12 @@ namespace module
 		/// </summary>
 		/// <returns></returns>
 		static void create_env(const std::string& lua_filepath,sol::this_state ts);
+		/// <summary>
+		/// 转INT
+		/// </summary>
+		/// <returns></returns>
+		static std::optional<int> toint(const sol::object& arg);
+
 
 		static void regist(sol::state* lua);
 	};