本篇在介绍lua绑定C++的一个最基本的模型,能够很方便的理解lua绑定C++对象后具体使用方式,主要是充分利用的元表的__index特性。
代码文件r_oo.cpp:
1 #include <iostream> 2 #include <cstring> 3 #include <stdlib.h> 4 extern "C" { 5 #include <lua.h> 6 #include <lualib.h> 7 #include <lauxlib.h> 8 } 9 #include "comm.h" 10 #include "luna.h" 11 #include "lunar.h" 12 13 using namespace std; 14 15 class Student 16 { 17 public: 18 Student(int iAge, int iScore):m_age(iAge), m_score(iScore){}; 19 ~Student(){cout<<"delete Student"<<endl;} 20 int getAge(){return m_age;} 21 void setAge(int iAge){m_age = iAge;} 22 static int autoGc(lua_State *L){ 23 Student** p = (Student**)lua_touserdata(L, 1); 24 cout << "auto gc. age: " << (*p)->m_age << " score: " << (*p)->m_score <<endl; 25 } 26 public: 27 int m_age; 28 int m_score; 29 }; 30 31 int create_stdent(lua_State *L) 32 { 33 Student** p = (Student**)lua_newuserdata(L, sizeof(Student*)); 34 *p = new Student(15, 100); 35 36 luaL_getmetatable(L, "MetaStu"); 37 lua_setmetatable(L, -2); 38 39 return 1; 40 } 41 42 int get_age(lua_State *L) 43 { 44 Student** p = (Student**)lua_touserdata(L, 1); 45 int iAge = (*p)->getAge(); 46 lua_pushinteger(L, iAge); 47 return 1; 48 } 49 50 int set_age(lua_State *L) 51 { 52 Student** p = (Student**)lua_touserdata(L, 1); 53 int iAge = lua_tointeger(L, 2); 54 (*p)->setAge(iAge); 55 return 0; 56 } 57 58 int auto_gc (lua_State *L) 59 { 60 Student** p = (Student**)lua_touserdata(L, 1); 61 (*p)-> autoGc(L); 62 return 0; 63 } 64 65 int lua_openStudent(lua_State *L) 66 { 67 const struct luaL_Reg list[] = {{"create", create_stdent}, {NULL, NULL}}; 68 luaL_register(L, "student", list); 69 70 if (luaL_newmetatable(L, "MetaStu")) 71 { 72 lua_pushcfunction(L, &get_age); 73 lua_setfield(L, -2, "getAge"); 74 lua_pushcfunction(L, &set_age); 75 lua_setfield(L, -2, "setAge"); 76 lua_pushcfunction(L, &auto_gc); 77 lua_setfield(L, -2, "__gc"); 78 lua_pushvalue(L, -1); 79 lua_setfield(L, -2, "__index"); 80 } 81 82 return 1; 83 } 84 85 int main(int argc, char* argv[]) 86 { 87 lua_State *L = luaL_newstate(); 88 luaL_openlibs(L); 89 luaL_dofile(L, "tree.lua"); 90 91 //bind to object use metatable 92 lua_openStudent(L); 93 print_stack(L); 94 95 luaL_dofile(L, "r_oo.lua"); 96 print_stack(L); 97 lua_settop(L, 0); 98 lua_close(L); 99 return 0; 100 }