C++调用Lua方法

test.lua文件

 



print("hello lua")
width=200
height=300
weight="this is String"

function max(num1,num2 ) 
    if(num1>num2)then
        return num1
    else
        return num2
    end 
end

C++ 代码

#include
#include
extern "C" {
#include "lua.h"  
#include "lauxlib.h"  
#include "lualib.h"  
}

#pragma comment(lib, "lua53.lib")//这个是在官网下载后源文件编译生成的静态库
lua_State *L;

double Cmax(double x, double y) {
	lua_getglobal(L, "max");
	lua_pushnumber(L, x);
	lua_pushnumber(L, y);

	if (lua_pcall(L, 2, 1, 0) != 0) {
		printf( "error running function 'f': %s\n", lua_tostring(L, -1));
	}

	if(!lua_isnumber(L,-1))
		printf("function 'f' must return a number\n");

	double z = lua_tonumber(L, -1);

	lua_pop(L, 1);
	return z;

}

lua_Integer getLuaInt(lua_State *L, int index) {//简化函数名
	return lua_tointeger(L, index);
}

lua_Integer getLuaInt(int index) {//简化函数参数
	return lua_tointeger(L, index);
}

const char * getLuaStr(lua_State *L, int index) {//简化函数名
	return lua_tostring(L, index);
}
const char * getLuaStr(int index) {//简化函数参数
	return lua_tostring(L, index);
}


int main()
{

	L = luaL_newstate();
	luaL_openlibs(L);

	if (luaL_loadfile(L, "test.lua") || lua_pcall(L, 0, 0, 0)) {
		printf("error%s\n", lua_tostring(L, -1));
		return -1;
	}

	lua_getglobal(L, "width");
	lua_getglobal(L, "height");
	lua_getglobal(L, "weight");
	printf("width = %d\n", getLuaInt(-3));
	printf("length = %d\n", getLuaInt(L, -2));
	printf("weight = %s\n", lua_tostring(L, -1));
	printf("weight = %s\n", getLuaStr(L, -1));
	printf("weight = %s\n", getLuaStr( -1));

	printf("%f\n", Cmax(9.0, 11.0));
	lua_close(L);
	system("pause");

	return 0;
}

 

你可能感兴趣的:(C++程序设计,Lua)