剛開始學(xué)習(xí)Luabind,所以算是一些簡單的筆記。
使用Luabind前要包含相關(guān)的頭文件,引入luabind命名空間。注意包含luabind.hpp并不會自動包含lua相關(guān)頭文件,要根據(jù)需要自己添加。
#include <luabind/luabind.hpp>
extern "C"
{
#include <lua.h>
#include <lualib.h>
}
using namespace luabind;
假設(shè)有以下類定義:
1 // TestClass.h
2 class TestClass
3 {
4 public:
5
6 TestClass(string s);
7
8 static TestClass* Singleton();
9
10 void Print();
11
12 private:
13
14 static TestClass* mSingleton;
15
16 string mString;
17 };
18
19 // TestClass.cpp
20 TestClass* TestClass::mSingleton = NULL;
21
22 TestClass::TestClass(string s)
23 {
24 mString = s;
25 }
26
27 TestClass* TestClass::Singleton()
28 {
29 if (TestClass::mSingleton == NULL)
30 {
31 return new TestClass("Hello");
32 }
33 else
34 {
35 return mSingleton;
36 }
37 }
38
39 void TestClass::Print()
40 {
41 cout << mString << endl;
42 }
創(chuàng)建一個bindClass函數(shù),用來進行導(dǎo)出類的相關(guān)工作
1 int bindClass(lua_State* L)
2 {
3 open(L);
4
5 module(L)
6 [
7 class_<TestClass>("TestClass")
8 .def(constructor<string>())
9 .def("Print", &TestClass::Print),
10 def("Singleton", TestClass::Singleton) // 請注意static成員函數(shù)Singleton()導(dǎo)出時和非靜態(tài)成員函數(shù)的寫法區(qū)別,
// 和全局函數(shù)的導(dǎo)出寫法一樣。
11 ];
12
13 return 0;
14 }
def
模版類中定義導(dǎo)出函數(shù)時,成員函數(shù)指針一定要用取地址符&,
如TestClass::Print()。
而自由函數(shù)和靜態(tài)函數(shù)可用可不用,如TestClass::Singleton()。
現(xiàn)在就可以寫代碼測試了:
// test.lua
1 testClass = Singleton()
2 testClass:Print()
// main.cpp
1 int _tmain(int argc, _TCHAR* argv[])
2 {
3 TestClass testClass("Hello from lua.");
4
5 lua_State* L = luaL_newstate();
6
7 init(L);
8
9 luaL_dofile(L, "add.lua");
10
11 lua_close(L);
12
13 return 0;
14 }
15
運行結(jié)果:
