勤能补拙,Expter

成都游戏Coder,记录游戏开发过程的笔记和心得!

c++调用lua脚本1(平台windows)

    通过c++调用lua 脚本,
    环境VC++6.0
    lua  sdk 5.1


   在调用前 先认识几个函数。
1. 调用lua_open()将创建一个指向Lua解释器的指针。
2. luaL_openlibs()函数加载Lua库。
3. 使用luaL_dofile()加载脚本并运行脚本。
4. lua_close()来关闭Lua指向解释器的指针。
 
5. 调用lua_getglobal()将add()函数压入栈顶,add()为lua函数。
6. 第一个参数x,通过调用lua_pushnumber()入栈。
7. 再次调用lua_pushnumber()将第二个参数入栈。
8. 使用lua_call()调用Lua函数。
9. 调用lua_tonumber()从栈顶取得函数的返回值。
10. lua_pop()移除栈顶的值。


代码
add.lua
1function add ( x, y )
2    return x + y
3end
4

main.cpp
#include <stdio.h>

extern "C" {
#include 
"lua.h"
#include 
"lualib.h"
#include 
"lauxlib.h"
}


/* the Lua interpreter */
lua_State  
* L;

int luaadd ( int x, int y )
{
    
int sum;
    
    
//函数名
    lua_getglobal(L, "add");
    
    
//第一个参数压栈
    lua_pushnumber(L, x);
    
    
//第二个参数压栈
    lua_pushnumber(L, y);

    
//调用函数
    lua_call(L, 21);
    
    
//得到返回值
    sum = (int)lua_tonumber(L, -1);
    lua_pop(L, 
1);
    
    
return sum;
}


int main ( int argc, char *argv[] )
{
    
int sum;
    
    
//创建一个指向Lua解释器的指针。
    L = lua_open();
    
    
//函数加载Lua库
    luaL_openlibs(L);

    
//加载脚本
    luaL_dofile(L,"add.lua");
    
    
//调用函数
    sum = luaadd( 1011);
    
    
// print the result 
    printf( "The sum is %d\n", sum );
    
    
//关闭 释放资源    
    lua_close(L);
    
    
return 0;
}



注意问题:
1.工程头文件lua.h等,编译器能找到,可以通过工具来设置头文件路径。
2. 添加lua5.1.lib到Object/library modules列表中。

测试结果
The sum is 21

关于lua的认识
http://www.cppblog.com/expter/archive/2008/12/24/70224.html

posted on 2009-01-18 22:04 expter 阅读(6581) 评论(7)  编辑 收藏 引用 所属分类: 其他学习笔记Visual C++ 笔记Lua游戏脚本

评论

# re: c++调用lua脚本1(平台windows) 2009-02-23 09:25 梦在天涯

恩,看来跟python的调用超级相似哦!  回复  更多评论   

# re: c++调用lua脚本1(平台windows) 2009-08-14 18:07 attacker2009

lua属于动态语言,和C++一起用功能还是很强大的。好像游戏里面用这种组合比较多  回复  更多评论   

# re: c++调用lua脚本1(平台windows) 2010-04-12 18:12 ii

 我的搜藏:[url=http://sousb.com/books/">http://sousb.com/books/]http://sousb.com/books/">http://sousb.com/books/[/url],这些书多是沉淀下来的极品,涵盖了C/C++,JAVA,Windows程序设计,MFC,数据结构和算法,软件工程,Linux,OpenGL/D3D 这些方向。
[img=http://photo.tuhigh.com/pics/1016/0411/284918t2076943659_d.jpg][/img]  回复  更多评论   

# re: c++调用lua脚本1(平台windows) 2010-09-25 22:14 zxb

谢谢,简单明了  回复  更多评论   

# re: c++调用lua脚本1(平台windows) 2010-11-23 11:43 江南烟雨梦

//调用函数
lua_call(L, 2, 1);

运行到此处,就直接退出了,这是为何?  回复  更多评论   

# re: c++调用lua脚本1(平台windows) 2010-11-24 22:37 expter

@江南烟雨梦
运行到哪儿退出,表示C++执行lua函数出错
看你绑定对象或者函数正确与否。
  回复  更多评论   


只有注册用户登录后才能发表评论。
网站导航: 博客园   IT新闻   BlogJava   知识库   博问   管理