總結一下lua與C的相互調用
列舉一個簡單的例子
1.創建一個win32控臺項目
2.下載lua庫,安裝.
3.設置動態鏈接(對於基礎不紮實的千萬記得設置),
項目>>屬性>>連接器>>附加依賴項>>
默認安裝位置 C:\Program Files (x86)\Lua\5.1\lib\lua5.1.lib(視步驟2的安裝位置)
C文件
// hellolua.cpp : 定義控制檯應用程序的入口點。
//
#include "stdafx.h"
#include <stdio.h>
extern "C" {
#include "lua.h"
#include "lualib.h"
#include "lauxlib.h"
}
int foo(lua_State *L)
{
/* get number of arguments */
int n = lua_tonumber(L, 1); //取lua中的值
/* push the n */
lua_pushnumber(L, n + 1); //壓入lua中的值
return 1;
}
int _tmain(int argc, _TCHAR* argv[])
{
/* initialize Lua */
lua_State *L = lua_open();
/* load Lua base libraries */
luaL_openlibs(L);
/* register our function */
lua_register(L, "foo", foo);
/* run the script */
luaL_dofile(L, "a.lua");
/* cleanup Lua */
lua_close(L);
/* pause */
printf("Press enter to exit...");
getchar();
return 0;
}
a.lua文件
print(foo(99))
1、使用
lua_tonumber
、lua_tostring
等函數,來取得傳入的參數,比如lua_tonumber(L,
1)
就是得到傳入的第一個參數,且類型爲數字2、使用
lua_pushnumber
、lua_pushstring
等函數,來將返回值壓入Lua的環境中,因爲Lua支持函數返回多個值,所以可以push多個返回值進Lua環境整個實例文件