1 // Copyright (c) 2016, Facebook, Inc. All rights reserved. 2 // This source code is licensed under both the GPLv2 (found in the 3 // COPYING file in the root directory) and Apache 2.0 License 4 // (found in the LICENSE.Apache file in the root directory). 5 6 #pragma once 7 // lua headers 8 extern "C" { 9 #include <lauxlib.h> 10 #include <lua.h> 11 #include <lualib.h> 12 } 13 14 #ifdef LUA 15 #include <string> 16 #include <vector> 17 18 #include "rocksdb/utilities/lua/rocks_lua_custom_library.h" 19 20 namespace ROCKSDB_NAMESPACE { 21 namespace lua { 22 class LuaStateWrapper { 23 public: LuaStateWrapper(const std::string & lua_script)24 explicit LuaStateWrapper(const std::string& lua_script) { 25 lua_state_ = luaL_newstate(); 26 Init(lua_script, {}); 27 } LuaStateWrapper(const std::string & lua_script,const std::vector<std::shared_ptr<RocksLuaCustomLibrary>> & libraries)28 LuaStateWrapper( 29 const std::string& lua_script, 30 const std::vector<std::shared_ptr<RocksLuaCustomLibrary>>& libraries) { 31 lua_state_ = luaL_newstate(); 32 Init(lua_script, libraries); 33 } GetLuaState()34 lua_State* GetLuaState() const { return lua_state_; } ~LuaStateWrapper()35 ~LuaStateWrapper() { lua_close(lua_state_); } 36 37 private: Init(const std::string & lua_script,const std::vector<std::shared_ptr<RocksLuaCustomLibrary>> & libraries)38 void Init( 39 const std::string& lua_script, 40 const std::vector<std::shared_ptr<RocksLuaCustomLibrary>>& libraries) { 41 if (lua_state_) { 42 luaL_openlibs(lua_state_); 43 for (const auto& library : libraries) { 44 luaL_openlib(lua_state_, library->Name(), library->Lib(), 0); 45 library->CustomSetup(lua_state_); 46 } 47 luaL_dostring(lua_state_, lua_script.c_str()); 48 } 49 } 50 51 lua_State* lua_state_; 52 }; 53 } // namespace lua 54 } // namespace ROCKSDB_NAMESPACE 55 #endif // LUA 56