• lua游戏开发易错踩坑录


    一。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
    

    三。判断Table表是否为空

    确定表是否为空的最有效方式(即,当前不包含数组样式值或字典样式值)
    方法一:

    if not next(myTable) then
        -- Table is empty
    end
    

    注意:这里的#操作符不够用,因为它只对表中的数组样式值进行操作 - 因此#{test=2}无法区分,#{}因为两者都返回0.还要注意检查表变量是否nil不够,因为我不寻找零值,而是具有0个条目(即{})的表格。
    方法二:

    if next(myTable) == nil then
        -- myTable is empty
     end
    

    测试:

    local myTable={[false]=0}
    if not next(myTable) then
        printlog("空表","shirln**********")
    else
        printlog("非空","shirln&&&&&&&&&&&")
    end
    if next(myTable) == nil then
        printlog("空表","shirln!!!!!!!!")
    else
        printlog("非空","shirln@@@@@@@@@@@")
    end
    

    输出:

    printlog("空表","shirln**********")
    printlog("非空","shirln@@@@@@@@@@@")
    

    可见,方法二比方法一更有效一些

    四。字符串的拼接使用string.format()

    如果需要显示类似于"10%"这样的字符串,如果直接使用string.format("%s%",10)会报如下错误:
    在这里插入图片描述
    可以考虑把百分号"%"符号当成一个值:string.format("%s%s",10,"%")

    五。更换图片sprite报错

    代码如下:

    function asset(path)
        return Asset:LoadAsset(path)
    end
    utils.findimage(this.gameObject, "bg").sprite = asset(path)
    

    错误:

    原因:Asset:LoadAsset加载的是任意资源,我们需要的是sprite资源
    解决办法:

    function asset(path)
        return LoadSprite(path)
    end
    utils.findimage(this.gameObject, "bg").sprite = asset(path)
    
  • 相关阅读:
    session在.ashx文件操作问题
    最全的CSS浏览器兼容问题
    详解div+css相对定位和绝对定位用法
    CSS前5课总结
    CSS元素定位6-10课
    宽度百分比单位的转换公式
    input点击链接另一个页面,各种操作
    Excel 导入 Sql Server出错——“文本被截断,或者一个或多个字符在目标代码页中没有匹配项”错误的解决
    jQuery:cookie插件的使用
    Jquery.Form和jquery.validate 的使用
  • 原文地址:https://www.cnblogs.com/shirln/p/11812525.html
Copyright © 2020-2023  润新知