歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> Lua入門之二:C/C++ 調用Lua及多個函數返回值的獲取

Lua入門之二:C/C++ 調用Lua及多個函數返回值的獲取

日期:2017/3/1 9:39:36   编辑:Linux編程

當 Lua 調用 C 函數的時候,使用和 C 調用 Lua 相同類型的棧來交互。C 函數從棧中獲取她的參數,調用結束後將返回結果放到棧中。為了區分返回結果和棧中的其他的值,每個 C 函數還會返回結果的個數(the function returns (in C) the number of results it is leaving on the stack.)。

// luacallcpp.cpp : 定義控制台應用程序的入口點。
//

#include "stdafx.h"

#include <stdio.h>


//lua頭文件
#ifdef __cplusplus
extern "C" {
#include "lua.h"
#include <lauxlib.h>
#include <lualib.h>
}
#else
#include <lua.h>
#include <lualib.h>
#include <lauxlib.h>
#endif

int static add(lua_State* L)
{
//獲取第一個參數
double x=lua_tonumber(L,1);
double y=lua_tonumber(L,2);
//返回值壓棧,壓入兩個返回值
lua_pushnumber(L,x+y);
lua_pushnumber(L,1000);

//返回值的個數,
return 2;
}


int _tmain(int argc, _TCHAR* argv[])
{

lua_State * L=NULL;

/* 初始化 Lua */
L = lua_open();

/* 載入Lua基本庫 */
luaL_openlibs(L);

/* 運行腳本 */
luaL_dofile(L, "./script/func.lua");

//函數入棧
lua_pushcfunction(L,add);
//設置全局函數名
lua_setglobal(L,"Add");
//調用lua函數LUACALLCPP來反調cpp中的add
lua_getglobal(L,"LUACALLCPP");
lua_pushnumber(L,10);
lua_pushnumber(L,34.33);
//兩個參數,兩個返回值
lua_pcall(L,2,2,0);
//取返回值二
printf("lua call cpp return val is %f \n",lua_tonumber(L,-1));
//取返回值一
printf("lua call cpp return val is %f \n",lua_tonumber(L,-2));


/* 清除Lua */
lua_close(L);

return 0;
}

---------------------------------------

--region *.lua
--Date
--此文件由[BabeLua]插件自動生成

print("func.lua hava been loaded")

function LUACALLCPP(x,y)
-- 調用c++中的函數
return Add(x,y)
--print(Add(x,y))
end

--endregion

運行結果:

Lua 語言 15 分鐘快速入門 http://www.linuxidc.com/Linux/2013-06/86582.htm

Lua程序設計(第2版)中文 PDF http://www.linuxidc.com/Linux/2013-03/81833.htm

Lua程序設計(第二版)閱讀筆記 http://www.linuxidc.com/Linux/2013-03/81834.htm

NetBSD 將支持用 Lua 腳本開發內核組件 http://www.linuxidc.com/Linux/2013-02/79527.htm

CentOS 編譯安裝 Lua LuaSocket http://www.linuxidc.com/Linux/2011-08/41105.htm

Lua 的詳細介紹:請點這裡
Lua 的下載地址:請點這裡

Copyright © Linux教程網 All Rights Reserved