C++ 调用 Lua

直接上代码:

1:c++代码

    • #include <lua.hpp>
      #include <LuaBridge/LuaBridge.h> #include <iostream>
      #include <string> class A
      {
      public:
      void action()
      {
      std::cout<<"Hello I am A\n";
      } virtual void doPrint(int a,int b)
      {
      std::cout<<"in A a:"<<a<<"b:"<<b<<std::endl;
      } std::string goodMan() const
      {
      return "goodman";
      }
      }; class B : public A
      {
      public:
      void hello(const std::string& info) const
      {
      std::cout<<"hello:"<<info<<std::endl;
      } virtual void doPrint(int a, int b) override
      {
      std::cout<<"in B just"<<(a + b) <<std::endl;
      }
      }; void globalFunction()
      {
      std::cout<<"hello this is a global func\n";
      } bool reloadLuaScript(lua_State* L, const std::string& luafile)
      {
      int state = luaL_dofile(L, luafile.c_str());
      if(state != LUA_OK)
      {
      return false;
      }
      return true;
      } void registerClassAndFunctions(lua_State* L)
      {
      using namespace luabridge;
      //注册全局函数和类函数
      getGlobalNamespace(L).addFunction("gloabalFunction",globalFunction);
      getGlobalNamespace(L)
      .beginClass<A>("A")
      .addFunction("action",&A::action)
      .addFunction("doPrint", &A::doPrint)
      .addFunction("goodMan", &A::goodMan)
      .endClass()
      .deriveClass<B,A>("B")
      .addFunction("hello", &B::hello)
      .endClass();
      } void testCallLua(lua_State* L)
      {
      A a;
      lua_getglobal(L,"testA");
      luabridge::push(L, &a);
      lua_pcall(L,1,0,0);
      } int main(int argc, char** argv)
      {
      lua_State* L = luaL_newstate(); luaL_openlibs(L);
      std::cout<<"try load file "<<argv[1]<<std::endl; auto ok = reloadLuaScript(L, argv[1]);
      if(!ok)
      {
      std::cout<<"load lua file failed\n";
      }
      else
      {
      registerClassAndFunctions(L);
      testCallLua(L);
      }
      lua_close(L);
      L = nullptr;
      }

2:Lua代码

    • --print("hello");
      --[[
      this is note
      这个是多行注释
      --]]
      print("This is myWorld!\n");
      function testA(a)
      a:action();
      a:doPrint(1,2);
      end
      ~
      ~

3:编译运行

    • [root@10-120-10-106 NewChart]# g++ -std=c++11 -o testlua testLua.cpp -llua -ldl
      [root@10-120-10-106 NewChart]# ./testlua abc.lua
      try load file abc.lua
      This is myWorld! Hello I am A
      in A a:1b:2

        

上一篇:windows 2008 R2 x64安装oracle12c报INS-30131


下一篇:mybatis动态sql