Lua使用Composer跨场景传参出现变量类型混淆报错问题
Corona Composer 跨场景传参异常解决方案
问题现象
使用Corona SDK的composer组件做场景跳转时传入自定义参数,目标场景访问参数时先后触发两类报错:
- 调用字符串查找方法时报错:
bad argument #1 to 'find' (string expected, got table) - 尝试将参数转为字符串时再次报错:
bad argument #1 to 'concat' (table expected, got string)
附调试代码与输出
场景1(发起跳转)代码
local function gotoOpt() scene:removeEventListener( "create", scene ) local customParams = { var1 = "scene3" } composer.gotoScene( "scene2", { effect="fade", time=1, params=customParams }) end
场景2(接收参数)代码
function scene:create( event ) local sceneGroup = self.view print(event.params.var1 == string) print(event.params.var1 == table) print(type(event.params.var1)) print(type(event.params.var1) == string) end
打印输出结果
四个print语句依次输出:
falsefalsestringfalse
错误原因
类型判断语法完全错误
Lua中不存在直接用== string/== table判断类型的写法:string、table是Lua内置标准库的表变量,不是类型标识;type()函数的返回值是字符串格式的类型名,比如返回"string"、"table"这类带引号的字符串值,你之前拿type返回的字符串和string库表做相等比较,自然永远返回false。参数取值层级错误
第一个find报错是因为你直接把event.params(也就是你传入的customParams表整体)传给了需要字符串参数的string.find方法,没有取到表内的var1字符串字段。
第二个concat报错是因为你误用了table.concat方法做字符串转换,这个方法要求第一个入参必须是表,你传入字符串自然触发报错。
修复方法
- 所有类型判断统一使用字符串字面量比较,正确写法:
-- 正确判断字符串类型 print(type(event.params.var1) == "string") -- 此时会正确输出true - 取值时注意参数层级:自定义参数都挂载在
event.params下,对应字段直接取即可,拿到的event.params.var1就是你传入的"scene3"字符串,可直接传给所有需要字符串参数的方法。 - 通用值转字符串使用
tostring()方法,不要用table.concat。
内容的提问来源于stack exchange,提问作者Nicholas O'Neal
相关产品推荐
相关产品推荐

