C++中调用Lua配置文件和响应函数示例

编程入门 行业动态 更新时间:2024-10-26 04:29:45

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); //第二个参数为调用函数的参数的个数,第三个为返回值的个数,第四个参数是错误处理函数,正常运行返回0 if(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 test width = 200 height = 500 function add(a,b) return a+b end math.randomseed(os.time()) function roll_num() return math.random(6) end

  • 0
  • 0
  • 0
  • 0
  • 0

更多推荐

C++中调用Lua配置文件和响应函数示例

本文发布于:2023-06-10 16:29:16,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/615040.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:示例   配置文件   函数   Lua

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!