为什么我的Lua脚本使用全局布尔变量时会触发sol3异常?
问题根因
你遇到的异常核心是Lua的字符串连接运算符..不会自动将布尔类型转换为字符串,仅支持自动转换数字类型,这就是为什么整数变量拼接正常、布尔变量拼接就出错的原因。
当你执行print("-- SampleBool1: " .. IsSampleBool1)时,Lua会直接抛出运行时错误:attempt to concatenate boolean value,该错误向上传递到sol3框架时,和你设置的异常处理逻辑、protected_function_result的取值逻辑冲突,就出现了你看到的sol3 panic提示。
修复方案
修改File2.lua中的打印逻辑,对布尔值做显式的字符串转换即可,两种常用写法:
- 方案1:用
tostring()包裹布尔变量
function PrintInfo(cpp_string) print("-- CPPString: " .. cpp_string); print("-- SampleString: " .. SampleString); print("-- SampleBool1: " .. tostring(IsSampleBool1)); print("-- SampleBool2: " .. tostring(IsSampleBool2)); print("-- SampleBool3: " .. tostring(IsSampleBool3)); print("-- SampleBool4: " .. tostring(IsSampleBool4)); print("-- SampleInt1: " .. SampleInt1); print("-- SampleInt2: " .. SampleInt2); print("-- End"); end
- 方案2:统一用
string.format做格式化,无需手动判断类型
function PrintInfo(cpp_string) print(string.format("-- CPPString: %s", cpp_string)); print(string.format("-- SampleString: %s", SampleString)); print(string.format("-- SampleBool1: %s", IsSampleBool1)); print(string.format("-- SampleBool2: %s", IsSampleBool2)); print(string.format("-- SampleBool3: %s", IsSampleBool3)); print(string.format("-- SampleBool4: %s", IsSampleBool4)); print(string.format("-- SampleInt1: %s", SampleInt1)); print(string.format("-- SampleInt2: %s", SampleInt2)); print("-- End"); end
额外说明
你提到的测试程序没有触发异常,大概率是测试时修改了布尔打印的逻辑没有同步到主程序,原生Lua只要执行布尔值和字符串的..拼接必然会抛出错误,不会出现无报错但后续内容不输出的情况,后续内容不输出就是因为脚本执行到拼接布尔的那一行就已经中断了。
内容的提问来源于stack exchange,提问作者Rick
相关产品推荐
相关产品推荐

