c++调用lua文件

来源:互联网 发布:linux强制删除用户 编辑:程序博客网 时间:2024/06/08 10:46

1.Lua文件

function func()print("aaaaaa")endfunc()width=800height=600background={r=1,g=0,b=0}function f(x,y)return x+yend

2.c++文件

#include <iostream>#include <lua.hpp>#include <lualib.h>#include <lauxlib.h>#include <limits.h>using namespace std;#pragma comment(lib,"lualib.lib")void load(lua_State*L,const char*fname,int* w,int*h){//加载文件if (LUA_OK == luaL_loadfile(L, fname))if (LUA_OK!=lua_pcall(L, 0, 0, 0))//运行Lua文件luaL_error(L, "不能运行配置.文件: %s", lua_tostring(L, -1));//获取全局变量lua_getglobal(L, "width");lua_getglobal(L, "height");if (0==lua_isnumber(L,-2))luaL_error(L, "'width'不是一个数字\n");if (0== lua_isnumber(L, -1))luaL_error(L, "'height'不是一个数字\n");*w = lua_tointeger(L, -2);*h = lua_tointeger(L, -1);}//获取table中的值int getfield(lua_State*L,const char*key){float result;lua_getfield(L, -1, key); //获取background[key]if (0==lua_isnumber(L, -1))luaL_error(L, "获取失败");result = (float)lua_tonumber(L, -1) * 255;lua_pop(L, 1);//删除数字return result;}//设置table 的值struct ColorTable {char* name;unsigned char red, gree, blue;}colortable[]{{"WHITE",255,255,255},{"RED",255,0,0},{NULL,0,0,0} //结尾};void setfield(lua_State*L,const char*index,int value){lua_pushnumber(L, (double)value / 255);lua_setfield(L, -2, index);}void setcolor(lua_State*L, struct ColorTable*ct){lua_newtable(L);setfield(L, "r", ct->red);//table.r=ct->rsetfield(L, "g", ct->gree);setfield(L, "b", ct->blue);lua_setglobal(L, ct->name); //'name'=table}//调用lua中的函数int f(lua_State*L,int x, int y){int z;//压入函数和参数lua_getglobal(L, "f");  //待调用的函数lua_pushnumber(L, x); //压入第一个参数lua_pushnumber(L, y);  //第二个参数//完成调用(2个参数,1个结果)if (lua_pcall(L, 2, 1, 0) != 0)luaL_error(L, "错误%s",lua_tostring(L,-1));//检索结果if (0==lua_isnumber(L,-1))luaL_error(L, "不是数字");z = lua_tonumber(L, -1); lua_pop(L, 1);//弹出返回值return z;}int main(){lua_State*L=luaL_newstate();luaL_openlibs(L);int width = 0, height = 0;load(L, "C:\\Users\\Administrator\\Desktop\\1.lua", &width, &height);cout << width<<""<<height<<endl;//获取table中的值lua_getglobal(L, "background");if (0==lua_istable(L, -1))luaL_error(L, "background不是table");int red =getfield(L,"r");int gree = getfield(L, "g");int blue = getfield(L, "b");cout << red << " " << gree << " " << blue << endl;//清空栈lua_settop(L, 0);//设置table的值int i = 0;while (colortable[i].name != NULL)setcolor(L, &colortable[i++]);lua_getglobal(L, "WHITE");if (0==lua_istable(L, -1))luaL_error(L, "background不是table");red = getfield(L, "r");gree = getfield(L, "g");blue = getfield(L, "b");cout << red << " " << gree << " " << blue << endl;//调用lua自定义函数int z = 0;z = f(L, 5, 1);cout << z << endl;system("pause");return 0;}