Advertisement
Guest User

Call C++ method from Lua script

a guest
Feb 16th, 2018
190
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.72 KB | None | 0 0
  1. #include <iostream>
  2.  
  3. #include "lua5.1/lua.hpp"
  4.  
  5. class Computer {
  6.     public:
  7.         Computer();
  8.         ~Computer();
  9.         void run();
  10.         void test(int i);
  11.     private:
  12.         lua_State *luaState;
  13. };
  14.  
  15. Computer * get_obj_pointer(lua_State *L)
  16. {
  17.     lua_getglobal(L, "computer");
  18.     if (!lua_istable(L, -1))
  19.         luaL_error(L, "Table 'computer' is not found!");
  20.  
  21.     lua_pushstring(L, "_self");
  22.     lua_gettable(L, -2);
  23.     if (!lua_isuserdata(L, -1))
  24.         luaL_error(L, "Value 'computer._self' is not found!");
  25.  
  26.     void *p = lua_touserdata(L, -1);
  27.     lua_pop(L, 1);
  28.  
  29.     return (Computer *) p;
  30. }
  31.  
  32. int test_wrap(lua_State *L)
  33. {
  34.     // read arguments
  35.     if(!lua_isnumber(L, -1))
  36.         luaL_error(L, "Expected a Number as a first argument!");
  37.     int i = lua_tonumber(L, -1);
  38.  
  39.     // restore pointer to object
  40.     Computer * pComp = get_obj_pointer(L);
  41.  
  42.     // call object method
  43.     if (pComp) {
  44.         pComp->test(i);
  45.     }
  46.  
  47.     return 0;
  48. }
  49.  
  50. Computer::Computer(void) {
  51.     luaState = luaL_newstate();
  52.     luaL_openlibs( luaState );
  53.  
  54.     lua_createtable(luaState, 0, 2);
  55.  
  56.     lua_pushlightuserdata(luaState, this);
  57.     lua_setfield(luaState, -2, "_self");
  58.  
  59.     lua_pushcfunction(luaState, test_wrap);
  60.     lua_setfield(luaState, -2, "test");
  61.  
  62.     lua_setglobal(luaState, "computer");
  63. }
  64.  
  65. Computer::~Computer(void) {
  66.     lua_close(luaState);
  67. }
  68.  
  69. void Computer::run(void) {
  70.     int err = luaL_dofile(luaState, "script.lua");
  71.     if (err) {
  72.        std::cout << "Error: " << lua_tostring(luaState, -1);
  73.        lua_pop(luaState, 1);
  74.     }
  75. }
  76.  
  77. void Computer::test(int i) {
  78.     std::cout << "test: " << i;
  79. }
  80.  
  81. int main()
  82. {
  83.     Computer c;
  84.     c.run();
  85.  
  86.     return 0;
  87. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement