在C中调用Lua作配置文件和响应函数
来源:互联网 发布:新媒体传播矩阵 编辑:程序博客网 时间:2024/06/05 20:53
Lua是脚本语言,最大的优势就是轻巧灵便,不用编译。当C的框架写好,只要更改lua的相应处理即可以更改功能,并且不用重新编译。以下是在C中调用Lua资源方法的示例程序:
C++端:
// Lua1.cpp : 定义控制台应用程序的入口点。//#include "stdafx.h"#include<stdio.h>extern "C" { //如不用extern会出现连接错误,编译成了C++文件#include <lua.h>#include <lualib.h>#include <lauxlib.h>}void load (lua_State *L,int *width,int *height){lua_getglobal(L,"width"); //获得Lua中变量的值,将其放入栈中lua_getglobal(L,"height");if(!lua_isnumber(L,-2)) //栈顶为-1,然后依次减少luaL_error(L,"`width' should be a number\n");if(!lua_isnumber(L,-1))luaL_error(L,"`height' should be a number\n");*width = (int)lua_tonumber(L,-2); //将栈顶元素转化为数字*height = (int)lua_tonumber(L,-1);}int add(lua_State *L,int a, int b){int sum=0;lua_getglobal(L,"add"); //函数也是变量,所以一个取法lua_pushnumber(L,a); //将变量传入lua_pushnumber(L,b); //第二个参数为调用函数的参数的个数,第三个为返回值的个数,第四个参数是错误处理函数,正常运行返回0if(lua_pcall(L,2,1,0) != 0){ luaL_error(L,"the lua load error! %s",lua_tostring(L,-1));} //函数的返回值已经传入栈中if(!lua_isnumber(L,-1)){ luaL_error(L,"the func run error! %s",lua_tostring(L,-1));}sum = (int)lua_tonumber(L,-1); //取栈顶元素将其转为数字,默认为double型 lua_pop(L,1) //将return元素移除return sum;}int get_num(lua_State *L){lua_getglobal(L,"roll_num");if(lua_pcall(L,0,1,0) != 0){luaL_error(L,"the lua load error! %s",lua_tostring(L,-1));}if(!lua_isnumber(L,-1)){luaL_error(L,"the func run error! %s",lua_tostring(L,-1));} int n = (int)lua_tonumber(L,-1);lua_pop(L,1);return n;}int _tmain(int argc, _TCHAR* argv[]){lua_State *L = lua_open();luaL_openlibs(L); //新版本库添加的方法if(luaL_loadfile(L,"cof.lua") || lua_pcall(L,0,0,0)){luaL_error(L,"loadfile error! %s \n",lua_tostring(L,-1));}int w=1,h=2;int sum;load(L,&w,&h);printf("width is %d ,height is %d\n",w,h);sum=add(L,w,h);printf("the sum is: %d \n",sum);bool flag = true;char c;while(flag){printf("Do you want to roll the number? \n");scanf("%c",&c);if(c == 'y' || c=='Y'){printf("rolling the number....\n the num is %d \n",get_num(L));}else flag=false;getchar();}getchar();return 0;}
Lua 文件:
-- config testwidth = 200height = 500function add(a,b)return a+bendmath.randomseed(os.time())function roll_num()return math.random(6)end
本篇博客出自 阿修罗道,转载请注明出处:http://blog.csdn.net/fansongy/article/details/6989160
- 在C中调用Lua作配置文件和响应函数
- Lua 在Lua中调用C函数
- 在Lua中调用C函数
- 在C中调用Lua代码
- lua作配置文件
- Ubuntu下安装Lua以及在C中调用Lua
- Lua 在C程序中调用Lua函数
- lua学习:lua作配置文件
- lua学习:lua作配置文件
- lua中调用C
- LUA中调用C
- LUA解析配置文件-C语言调用
- 在LUA脚本中调用C/C++函数
- 如何在c/c++中调用LUA函数
- 在c中调用lua函数,获取返回值等
- 在C中调用lua的内置函数string.gsub
- 在c中调用lua函数,获取返回值等
- 在Lua代码中调用c/C++函数
- 随机洗牌算法
- SSH中出现java.lang.NoSuchMethodError: org.objectweb.asm.ClassWriter.(I)V
- c++ vector去掉重复的
- 一个硬件高手的设计经验分享
- java.lang.IllegalStateException: No WebApplicationContext found: no ContextLoaderListener registered
- 在C中调用Lua作配置文件和响应函数
- 编写可复用的自定义按钮
- 每个程序员都应该学习使用Python或Ruby
- IT项目管理的六种错误思维
- ASP.NET_FORM表单验证_单点登录_Nomads (FormsAuthentication)
- 程序员们 不要想一辈子靠技术混饭吃
- 初试mini2440 nandflash驱动移植
- UML中类之间的关系
- HTML与SHTML的区别