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

cocos2dx3.0下sqlite的C++与lua绑定

2014-01-27 12:16 453 查看
1.首先下载luaSqlite的源代码http://lua.sqlite.org/index.cgi/index

下载sqlite的源代码 http://sqlite.org/
 

2.解压。应该有5个文件     lsqlite3.c

                                          shell.c

                                          sqlite3.c

                                          sqlite3.h

                                          sqlite3ext.h

 

把这几个文件放到\cocos2d\cocos\scripting\lua\bindings路径下

 

3.在vs2012的解决方案中,选择liblua的项目,选择cocos2dx_support文件夹,把这几个文件导入进去。

4.在cocos2dx_support文件夹下新建一个文件lsqlite3.h。并写入如下代码保存。

#ifndef __LSQLITE3_H__
#define __LSQLITE3_H__

#ifdef __cplusplus
extern "C" {
#endif
#include "tolua++.h"
#ifdef __cplusplus
}
#endif

extern "C" int luaopen_lsqlite3(lua_State* L);
#endif


 

5.在 cocos2dx_support文件夹找到一个CCLuaStack.cpp的文件。 
把刚才新建的头文件包含进去。
在该文件的init函数下增加如下代码  

register_all_cocos2dx_extension(_state);
register_all_cocos2dx_deprecated(_state);
register_cocos2dx_extension_CCBProxy(_state);
register_cocos2dx_event_releated(_state);
tolua_opengl_open(_state);
register_all_cocos2dx_gui(_state);
register_all_cocos2dx_studio(_state);
register_all_cocos2dx_manual(_state);
register_all_cocos2dx_extension_manual(_state);
register_all_cocos2dx_manual_deprecated(_state);
register_all_cocos2dx_coco_studio_manual(_state);
register_all_cocos2dx_gui_manual(_state);
register_all_cocos2dx_spine(_state);
register_all_cocos2dx_spine_manual(_state);
register_glnode_manual(_state);
luaopen_lsqlite3(_state); //该行为新增代码。


 

编译构建项目

 

 

6.下面我们测试一下。

在你的lua文件中增加如下两行

local sqlite3 =require("sqlite3")
print("sqlite3  version"..sqlite3.version())


 

输出结果为

[LUA-print] sqlite3  version3.8.3

7.注意事项

lsplite.c编译可能会报错,找到如下段做如下修改

static void db_update_hook_callback(void *user, int op, char const *dbname, char const *tblname, sqlite3_int64 rowid) {
sdb *db = (sdb*)user;
lua_State *L = db->L;
int top = lua_gettop(L);
lua_Number n = (lua_Number)rowid; //移到这,c语言所有变量要在开头定义
/* setup lua callback call */
lua_rawgeti(L, LUA_REGISTRYINDEX, db->update_hook_cb);    /* get callback */
lua_rawgeti(L, LUA_REGISTRYINDEX, db->update_hook_udata); /* get callback user data */
lua_pushnumber(L, (lua_Number )op);
lua_pushstring(L, dbname); /* update_hook database name */
lua_pushstring(L, tblname); /* update_hook database name */
//lua_Number n = (lua_Number)rowid; //把这句移到前面
if (n == rowid)
lua_pushnumber(L, n);
else
lua_pushfstring(L, "%ll", rowid);

/* call lua function */
lua_pcall(L, 5, 0, 0);
/* ignore any error generated by this function */

lua_settop(L, top);
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  sqlite cocos2dx lua