没有合适的资源?快使用搜索试试~ 我知道了~
lua作为小巧精悍的脚本语言,易于嵌入c/c++中 , 广泛应用于游戏AI ,实际上在任何经常变化的逻辑上都可以使用lua实现,配合c/c++实现的底层接口服务,能够大大降低系统的维护成本。下面对lua和c/c++的交互调用做一个实例分析: lua提供了API用于在c/c++中构造lua的运行环境,相关接口如下: //创建lua运行上下文 lua_State* luaL_newstate(void) ; //加载lua脚本文件 int luaL_loadfile(lua_State *L, const char *filename); lua和c/c++的数据交互通过”栈”进行 ,操作数据时
资源推荐
资源详情
资源评论
Lua和和C/C++互相调用实例分析互相调用实例分析
lua作为小巧精悍的脚本语言,易于嵌入c/c++中 , 广泛应用于游戏AI ,实际上在任何经常变化的逻辑上都可以使用lua实现,
配合c/c++实现的底层接口服务,能够大大降低系统的维护成本。下面对lua和c/c++的交互调用做一个实例分析:
lua提供了API用于在c/c++中构造lua的运行环境,相关接口如下:
//创建lua运行上下文
lua_State*
luaL_newstate(void) ;
//加载lua脚本文件
int luaL_loadfile(lua_State *L, const
char *filename);
lua和c/c++的数据交互通过”栈”进行
,操作数据时,首先将数据拷贝到”栈”上,然后获取数据,栈中的每个数据通过索引值进行定位,索引值为正时表示相对于栈底
的偏移索引,索引值为负时表示相对于栈顶的偏移索引,索引值以1或-1为起始值,因此栈顶索引值永远为-1,栈底索引值永远
为1 。 “栈”相当于数据在lua和c/c++之间的中转地。每种数据都有相应的存取接口 。
数据入”栈”接口:
void (lua_pushnil) (lua_State *L);
void (lua_pushnumber) (lua_State *L, lua_Number n);
void (lua_pushinteger) (lua_State *L, lua_Integer n);
void (lua_pushlstring) (lua_State *L, const char *s, size_t l);
void (lua_pushstring) (lua_State *L, const char *s);
void (lua_pushboolean) (lua_State *L, int b);
void (lua_pushcclosure) (lua_State *L, lua_CFunction fn, int n);
数据获取接口:
lua_Number (lua_tonumber) (lua_State *L, int idx);
lua_Integer (lua_tointeger) (lua_State *L, int idx);
int (lua_toboolean) (lua_State *L, int idx);
const char *(lua_tolstring) (lua_State *L, int idx, size_t *len);
lua_CFunction (lua_tocfunction) (lua_State *L, int idx);
“栈”操作接口:
int (lua_gettop) (lua_State *L);
void (lua_settop) (lua_State *L, int idx);
void (lua_pushvalue) (lua_State *L, int idx);
void (lua_remove) (lua_State *L, int idx);
void (lua_insert) (lua_State *L, int idx);
void (lua_replace) (lua_State *L, int idx);
int (lua_checkstack) (lua_State *L, int sz);
lua中定义的变量和函数存放在一个全局table中,索引值为LUA_GLOBALSINDEX,table相关操作接口:
void (lua_gettable) (lua_State *L, int idx);
void (lua_getfield) (lua_State *L, int idx, const char *k);
void (lua_settable) (lua_State *L, int idx);
void (lua_setfield) (lua_State *L, int idx, const char *k);
当”栈”中包含执行脚本需要的所有要素(函数名和参数)后,调用lua_pcall执行脚本:
int (lua_pcall) (lua_State *L, int nargs, int nresults, int errfunc);
下面进行实例说明:
func.lua
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
//lua头文件
#include <lua.h>
#include <lualib.h>
资源评论
weixin_38638163
- 粉丝: 3
- 资源: 975
上传资源 快速赚钱
- 我的内容管理 展开
- 我的资源 快来上传第一个资源
- 我的收益 登录查看自己的收益
- 我的积分 登录查看自己的积分
- 我的C币 登录后查看C币余额
- 我的收藏
- 我的下载
- 下载帮助
安全验证
文档复制为VIP权益,开通VIP直接复制
信息提交成功