1. 程式人生 > >C++與Lua5.3.2的相互呼叫

C++與Lua5.3.2的相互呼叫

重Lua官網下載最新的Lua5.3.2解壓後把src檔案下的所有檔案(Lua.c,Luac.c除外)複製到專案的目錄下,並新增到專案中,

建立一個Lua指令碼檔案

--region *.lua  
--Date  
--此檔案由[BabeLua]外掛自動生成  

print("lua script func.lua have been load ") 
avg, sum = average(10, 20, 30, 40, 50)
print("The average is ", avg)
print("The sum is ", sum)

function add(x,y)
    return
x+y+x*y end --endregion

C++檔案如下

#include <iostream>
#include <stdio.h>  

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

using namespace std;

lua_State* L;

static int average(lua_State *L)
{
    //返回棧中元素的個數  
    int n = lua_gettop(L);
    double
sum = 0; int i; for (i = 1; i <= n; i++) { if (!lua_isnumber(L, i)) { lua_pushstring(L, "Incorrect argument to 'average'"); lua_error(L); } sum += lua_tonumber(L, i); } /* push the average */ lua_pushnumber(L, sum / n); /* push the sum */
lua_pushnumber(L, sum); /* return the number of results */ return 2; } void main() { //cout << "Hello CML" << endl; /* 初始化 Lua */ L = luaL_newstate(); /* 載入Lua基本庫 */ luaL_openlibs(L); /* register our function */ lua_register(L, "average", average); /* 執行指令碼 */ luaL_dofile(L, "e://lua1.lua"); lua_getglobal(L, "avg"); int avg = lua_tointeger(L, -1); lua_pop(L, 1); lua_getglobal(L, "sum"); int sum = lua_tointeger(L, -1); lua_getglobal(L, "add"); lua_pushinteger(L, 10); lua_pushinteger(L, 20); lua_pcall(L, 2, 1, 0); printf("lua add function return val is %d \n", lua_tointeger(L, -1)); /* 清除Lua */ lua_close(L); /* 暫停 */ printf("Press enter to exit…"); getchar(); }