lua游戏开发易错踩坑录

亡梦爱人 提交于 2019-12-04 00:03:20

一。local

local函数一定要在调用之前定义(切记,不然会报错或者不能调用该函数)
情况1:监听调此函数后定义

base.model:addlistener("被监听的函数", 监听成功的回调函数)
local function 监听成功的回调函数()
    --处理
end

上面代码运行游戏将会报如下错:
在这里插入图片描述
handler parameter in addlistener function has to be function, nil not right

二。协程

停止协程前将协程中某变量或组建置空
在这里插入图片描述
使用协程做计时功能应注意
1.协程中用到的组件,变量等被置空前,应该将协程置空
2.置空协程之前应停止协程
3.为了确保同一个协程同时只运行一次,可在协程开始前添加安全代码:判断改协程是否存在,存在则停止协程并将协程置空
实现方法:

local function setMyTime()
    --注意(3)
    if this.countdown then
        coroutine.stop(this.countdown)
        this.countdown = nil
    end
    this.countdown = coroutine.start(function()
        while true do
            this.tm=this.tm-1--用到的变量
            coroutine.wait(1)
        end
    end)
end
注意(2)
if this.countdown then
    coroutine.stop(this.countdown)
    --注意(1)
    this.countdown = nil
end
--假设此时需要对this.tm置空
this.tm=nil
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!