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");
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
免责声明:本站文章均来自网站采集或用户投稿,网站不提供任何软件下载或自行开发的软件!
如有用户或公司发现本站内容信息存在侵权行为,请邮件告知! 858582#qq.com
暂无“C++中调用Lua配置文件和响应函数示例”评论...
更新动态
2025年10月27日
2025年10月27日
- 小骆驼-《草原狼2(蓝光CD)》[原抓WAV+CUE]
- 群星《欢迎来到我身边 电影原声专辑》[320K/MP3][105.02MB]
- 群星《欢迎来到我身边 电影原声专辑》[FLAC/分轨][480.9MB]
- 雷婷《梦里蓝天HQⅡ》 2023头版限量编号低速原抓[WAV+CUE][463M]
- 群星《2024好听新歌42》AI调整音效【WAV分轨】
- 王思雨-《思念陪着鸿雁飞》WAV
- 王思雨《喜马拉雅HQ》头版限量编号[WAV+CUE]
- 李健《无时无刻》[WAV+CUE][590M]
- 陈奕迅《酝酿》[WAV分轨][502M]
- 卓依婷《化蝶》2CD[WAV+CUE][1.1G]
- 群星《吉他王(黑胶CD)》[WAV+CUE]
- 齐秦《穿乐(穿越)》[WAV+CUE]
- 发烧珍品《数位CD音响测试-动向效果(九)》【WAV+CUE】
- 邝美云《邝美云精装歌集》[DSF][1.6G]
- 吕方《爱一回伤一回》[WAV+CUE][454M]