您的位置:首页 > 移动开发 > Cocos引擎

cocos lua 关于error: syntax error during pre-compilation

2016-06-23 16:36 1041 查看
  借助于sublime Text,在cocos 3.8中编写lua脚本的过程中,我相信“error:syntax error during pre-compliation”(编译语法错误)遇到的话,似乎是家常便饭,然而几千行的脚本,错误到底在哪里呢,能否有一个更为详细的定位呢。这个就是我今天要说的。

(1) 首先,根据“error: syntax error during pre-compilation”在项目中查看其相关的位置,在LuaStack::luaLoadBuffer(...)中,你会发现相关的代码实现,其主要代码如下:

switch (r)
{
case LUA_ERRSYNTAX:     // 编译出错
CCLOG("[LUA ERROR] load \"%s\", error: syntax error during pre-compilation.", chunkName);
break;
case LUA_ERRMEM:        // 内存分配错误
CCLOG("[LUA ERROR] load \"%s\", error: memory allocation error.", chunkName);
break;
case LUA_ERRRUN:        // 运行错误
CCLOG("[LUA ERROR] load \"%s\", error: run error.", chunkName);
break;
case LUA_YIELD:         // 线程被挂起
CCLOG("[LUA ERROR] load \"%s\", error: thread has suspended.", chunkName);
break;
case LUA_ERRFILE:
CCLOG("[LUA ERROR] load \"%s\", error: cannot open/read file.", chunkName);
break;
case LUA_ERRERR:        // 运行错误处理函数时发生错误
CCLOG("[LUA ERROR] load \"%s\", while running the error handler function.", chunkName);
break;
default:
CCLOG("[LUA ERROR] load \"%s\", error: unknown.", chunkName);
}
// (2)处添加部分代码

const char* error = lua_tostring(L, -1);
CCLOG("[LUA ERROR] error result: %s",error);
lua_pop(L, 1);


相关宏的大概含义,已添加注释,不再赘述了。

(2) 针对于lua的错误,一般分为编译时错误和运行时错误;但无论怎样,出现错误时,都能将错误信息返回到堆栈的最顶层,所以,针对于编译错误,可以通过如下的代码来打印错误信息:

const char* error = lua_tostring(L, -1);
CCLOG("[LUA ERROR] error result: %s",error);
lua_pop(L, 1);


而针对于运行错误,一般情况下,你可以参考如下代码:

-- lua提供,调用其他函数,可以捕捉到错误,第一个参数为要调用的函数, 第二个参数为捕捉到错误时所调用的函数
-- 返回的参数status为错误状态, msg为错误信息
local status, msg = xpcall(main, __G__TRACKBACK__)
if not status then
print(msg)
end


优化的方案出来了,将(2)处的第一块代码,添加到(1)处中,这样的话,来参考一个例子看看效果,如图所示:

我在42行处的末尾,添加了一个中文符号“;”,编译后,运行脚本,提示错误:

在这种情况下,我相信比之前查找错误要好很多,感谢!

感谢原作者:http://blog.csdn.net/dch4890164/article/details/4455208
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  cocos2d-x lua