为什么我的 Lua 脚本为全局布尔变量抛出异常?

我正在尝试为我的 Lua 脚本中的全局变量赋予布尔默认值,然后输出或利用该值。但是,在我的主程序中,这会抛出异常...在以下的小程序中,我没有抛出异常...但是一旦我尝试输出布尔值,它就不会输出其他任何东西(即使不是布尔值)...有人知道发生了什么吗?我已经花了数小时在这上面了...

这是我在我的主程序上得到的异常,但不是在我的示例程序上。当我将变量变为布尔值时,才会抛出此异常(如果是整数,则不会发生)。

[sol3] An error occurred and panic has been invoked: stack index 1, expected string, received no value: bad get from protected_function_result (is not an error)

Main.cpp

#pragma warning(push, 0)
#define SOL_ALL_SAFETIES_ON 1
#include "sol.hpp"
#pragma warning(pop)

int ExceptionHandler(
   lua_State* L,
   sol::optional<const std::exception&> maybe_exception,
   sol::string_view description)
{
   if (maybe_exception) {
      const std::exception& ex = *maybe_exception;
      std::cout << "Lua 错误1: " << std::string(ex.what());
   }
   else {
      std::cout << "Lua 错误2: " << std::string(description.data(), description.size());
   }

   return sol::stack::push(L, description);
}

int main()
{
   sol::state lua_state;
   lua_state.open_libraries(sol::lib::base);
   lua_state.set_exception_handler(&ExceptionHandler);

   sol::protected_function_result result = lua_state.safe_script_file("File1.lua", &sol::script_pass_on_error);
   if (!result.valid())
   {
      sol::error err = result;
      std::cout << err.what();
   }
   else
   {
      lua_state["PrintInfo"]("CPP 字符串");
   }

   system("pause");
}

File1.lua

SampleString = "示例";
IsSampleBool1 = false;
IsSampleBool2 = false;
IsSampleBool3 = false;
IsSampleBool4 = false;
SampleInt1 = 0;
SampleInt2 = 1;

dofile("File2.lua");

File2.lua

function PrintInfo(cpp_string)
    print("--       CPPString: " .. cpp_string);
    print("--       SampleString: " .. SampleString);
    print("--       SampleBool1: " .. IsSampleBool1);
    print("--       SampleBool2: " .. IsSampleBool2);
    print("--       SampleBool3: " .. IsSampleBool3);
    print("--       SampleBool4: " .. IsSampleBool4);
    print("--       SampleInt1: " .. SampleInt1);
    print("--       SampleInt2: " .. SampleInt2);
    print("--       结束");
end

原文链接 https://stackoverflow.com/questions/69293430

点赞