既然是從零開始,那么就搞的傻瓜一點,就算是手把手教了. 哈哈.
一下內(nèi)容在vs2005實現(xiàn)
新建一個空的win32控制臺項目.
1.首先我們來配置頭文件和庫文件:
頭文件:
D:\Lua\lua-5.1.4\src

D:\Lua\luabind-0.8.1

D:\Lua\boost_1_41_0


庫文件:無.見代碼.
下面就是cpp內(nèi)容了:注釋都是個人理解,如果您覺得不對
#include <luabind/luabind.hpp>
#pragma comment(lib,"lualib.lib") //可能你會問,lualib.lib是哪里來的? 這是我自己編譯luabind得到

//的, 如果你不知道怎么編譯,參考下我的另一篇文章<從零開始使用luabind>
#include <iostream>
using namespace std;
using namespace luabind;


class testlua//寫一個測試類,包括一些簡單的方法.


{
public:

testlua(std::string s):m_str(s)
{};
void myprint()

{
cout << m_str << endl;
}

void setstr(std::string s)
{ m_str = s;};
private:
std::string m_str;
};


int main()


{
lua_State *L = luaL_newstate();//新建一個lua_State,或者叫做創(chuàng)建lua狀態(tài)
luabind::open(L);//為改lua狀態(tài)打開所有l(wèi)ua庫

//把寫好的類綁定到lua,以下內(nèi)容為讀書所得,我看的是missdeer同學(xué)翻譯的luabindmanual一書.
//相信好學(xué)的你,如果不明白這是怎么用的,一定會找來這書讀一讀的,當(dāng)然我也很樂意和您分享(Q:625425901)

module(L)

[
class_<testlua>("testlua")
.def(constructor<const std::string>())
.def("myprint",&testlua::myprint)//開放這兩個函數(shù)給lua使用
.def("setstr", &testlua::setstr)
];

luaL_dofile(L,"test.lua");//執(zhí)行l(wèi)ua文件,稍后你會看到test.lua文件的內(nèi)容
lua_close(L);//關(guān)閉lua狀態(tài)
return 0;
}


以下是test.lua內(nèi)容:


local a = testlua("hello lua!");--看不懂?如果我說它在c里是這樣的: testlua obj = testlua("hello lua!"),看懂了么?恩,構(gòu)建testlua類的對象.

a:myprint();//調(diào)用方法

a:setstr("yes lua!");

a:myprint();


--接下來我們在lua里嘗試如下代碼:

a:hisprint();

--你也許會問,這個函數(shù)不存在啊.確實不存在,但是程序并沒有報錯,所以或許我們需要其他的代碼來處理這種錯誤的調(diào)用,后話了,慢慢來.


好了,執(zhí)行一下C代碼,你應(yīng)該會看到想要的結(jié)果了.相信不少同學(xué)看到這里已經(jīng)開始計劃寫一個類,用來隨心所欲的開放你的C方法給lua使用了.先到這里.

歡迎批評指正.