欢迎来到淼淼之森的博客小站。  交流请加我微信好友: studyjava。  也欢迎关注同名公众号:Java学习之道

lua游戏开发易错踩坑录

  |   0 评论   |   0 浏览

一。local

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

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

上面代码运行游戏将会报如下错:

1.png

handler parameter in addlistener function has to be function, nil not right

二。协程

停止协程前将协程中某变量或组建置空

2.png

使用协程做计时功能应注意
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)会报如下错误:

3.png

可以考虑把百分号"%"符号当成一个值:string.format("%s%s",10,"%")

五。更换图片sprite报错

代码如下:

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

错误:

4.png

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

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

标题:lua游戏开发易错踩坑录
作者:jerrycookie
地址:https://www.mmzsblog.cn/articles/2020/06/21/1592708371059.html

如未加特殊说明,文章均为原创,转载必须注明出处。均采用CC BY-SA 4.0 协议

本网站发布的内容(图片、视频和文字)以原创、转载和分享网络内容为主,如果涉及侵权请尽快告知,我们将会在第一时间删除。若本站转载文章遗漏了原文链接,请及时告知,我们将做删除处理!文章观点不代表本网站立场,如需处理请联系首页客服。
• 网站转载须在文章起始位置标注作者及原文连接,否则保留追究法律责任的权利。
• 公众号转载请联系网站首页的微信号申请白名单!

个人微信公众号 ↓↓↓                 

微信搜一搜爱上游戏开发