Lua調用C++方法

test.lua




width=200
height=300
weight="this is String"

function LuaInput()
 
 a=io.read();
 print(a)

 end

function max(num1,num2 ) 

	LuaInput()
    if(num1>num2)then
        return num1
    else
        return num2
    end 
end

html = [[
塊狀字符串
]]
print(html)

---在此處調用C++方法
findWay()




useLua.cpp

 

#include<stdio.h>
#include<stdlib.h>

#include<iostream>
using namespace std;
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 findWay() {

	cout << "尋路指令被執行" << endl;

	return 1;
}


extern "C" int findWay(lua_State *L) {
	return findWay();
}



int main()
{

	L = luaL_newstate();
	luaL_openlibs(L);



	lua_register(L, "findWay", findWay);

	//內部自己執行
	//luaL_dostring(L, "findWay()");

	//腳本文件執行
	luaL_dofile(L,"test.lua");


/*
	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;
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章