您的位置:首页 > 编程语言 > Lua

c++调用lua文件

2017-06-26 16:26 399 查看

1.Lua文件

function func()
print("aaaaaa")
end

func()

width=800
height=600

background={r=1,g=0,b=0}

function f(x,y)
return x+y
end

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->r
setfield(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
8ffe
, 5, 1);
cout << z << endl;

system("pause");
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: