?login_element?

Subversion Repositories NedoOS

Rev

Blame | Last modification | View Log | Download | RSS feed

  1. // https://github.com/vinniefalco/LuaBridge
  2. // Copyright 2019, Dmitry Tarakanov
  3. // Copyright 2012, Vinnie Falco <vinnie.falco@gmail.com>
  4. // Copyright 2007, Nathan Reed
  5. // SPDX-License-Identifier: MIT
  6.  
  7. #pragma once
  8.  
  9. #include "Lua/LuaLibrary.h"
  10.  
  11. #include "LuaBridge/LuaBridge.h"
  12.  
  13. #include <gtest/gtest.h>
  14.  
  15. #include <stdexcept>
  16.  
  17. // traceback function, adapted from lua.c
  18. // when a runtime error occurs, this will append the call stack to the error message
  19. //
  20. inline int traceback(lua_State* L)
  21. {
  22.     // look up Lua's 'debug.traceback' function
  23.     lua_getglobal(L, "debug");
  24.     if (!lua_istable(L, -1))
  25.     {
  26.         lua_pop(L, 1);
  27.         return 1;
  28.     }
  29.     lua_getfield(L, -1, "traceback");
  30.     if (!lua_isfunction(L, -1))
  31.     {
  32.         lua_pop(L, 2);
  33.         return 1;
  34.     }
  35.     lua_pushvalue(L, 1); /* pass error message */
  36.     lua_pushinteger(L, 2); /* skip this function and traceback */
  37.     lua_call(L, 2, 1); /* call debug.traceback */
  38.     return 1;
  39. }
  40.  
  41. /// Base test class. Introduces the global 'result' variable,
  42. /// used for checking of C++ - Lua interoperation.
  43. ///
  44. struct TestBase : public ::testing::Test
  45. {
  46.     lua_State* L = nullptr;
  47.  
  48.     void SetUp() override
  49.     {
  50.         L = nullptr;
  51.         L = luaL_newstate();
  52.         luaL_openlibs(L);
  53.         lua_pushcfunction(L, &traceback);
  54.     }
  55.  
  56.     void TearDown() override
  57.     {
  58.         if (L != nullptr)
  59.         {
  60.             lua_close(L);
  61.         }
  62.     }
  63.  
  64.     void runLua(const std::string& script) const
  65.     {
  66.         if (luaL_loadstring(L, script.c_str()) != 0)
  67.         {
  68.             throw std::runtime_error(lua_tostring(L, -1));
  69.         }
  70.  
  71.         if (lua_pcall(L, 0, 0, -2) != 0)
  72.         {
  73.             throw std::runtime_error(lua_tostring(L, -1));
  74.         }
  75.     }
  76.  
  77.     template<class T = luabridge::LuaRef>
  78.     T result() const
  79.     {
  80.         return luabridge::getGlobal(L, "result").cast<T>();
  81.     }
  82.  
  83.     void resetResult() const { luabridge::setGlobal(L, luabridge::LuaRef(L), "result"); }
  84.  
  85.     void printStack() const
  86.     {
  87.         std::cerr << "===== Stack =====\n";
  88.         for (int i = 1; i <= lua_gettop(L); ++i)
  89.         {
  90.             std::cerr << "@" << i << " = " << luabridge::LuaRef::fromStack(L, i) << "\n";
  91.         }
  92.     }
  93. };
  94.