LuaBinder.h 5.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213
  1. // Copyright (C) 2009-2015, Panagiotis Christopoulos Charitos.
  2. // All rights reserved.
  3. // Code licensed under the BSD License.
  4. // http://www.anki3d.org/LICENSE
  5. #pragma once
  6. #include "anki/util/Assert.h"
  7. #include "anki/util/StdTypes.h"
  8. #include "anki/util/Allocator.h"
  9. #include "anki/util/String.h"
  10. #include "anki/util/Functions.h"
  11. #include <lua.hpp>
  12. #ifndef ANKI_LUA_HPP
  13. # error "Wrong LUA header included"
  14. #endif
  15. namespace anki {
  16. /// LUA userdata.
  17. class UserData
  18. {
  19. public:
  20. /// @note NEVER ADD A DESTRUCTOR. LUA cannot call that.
  21. ~UserData() = delete;
  22. I64 getSig() const
  23. {
  24. return m_sig;
  25. }
  26. void initGarbageCollected(I64 sig)
  27. {
  28. m_sig = sig;
  29. m_addressAndGarbageCollect = GC_MASK;
  30. }
  31. void initPointed(I64 sig, void* ptrToObject)
  32. {
  33. m_sig = sig;
  34. U64 addr = ptrToNumber(ptrToObject);
  35. ANKI_ASSERT((addr & GC_MASK) == 0
  36. && "Address too high, cannot encode a flag");
  37. m_addressAndGarbageCollect = addr;
  38. }
  39. Bool isGarbageCollected() const
  40. {
  41. return m_addressAndGarbageCollect == GC_MASK;
  42. }
  43. template<typename T>
  44. T* getData()
  45. {
  46. T* out = nullptr;
  47. if(isGarbageCollected())
  48. {
  49. // Garbage collected
  50. PtrSize mem = ptrToNumber(this);
  51. mem += getAlignedRoundUp(alignof(T), sizeof(UserData));
  52. out = numberToPtr<T*>(mem);
  53. }
  54. else
  55. {
  56. // Pointed
  57. PtrSize mem = static_cast<PtrSize>(m_addressAndGarbageCollect);
  58. out = numberToPtr<T*>(mem);
  59. }
  60. ANKI_ASSERT(out);
  61. ANKI_ASSERT(isAligned(alignof(T), out));
  62. return out;
  63. }
  64. template<typename T>
  65. static PtrSize computeSizeForGarbageCollected()
  66. {
  67. return getAlignedRoundUp(alignof(T), sizeof(UserData)) + sizeof(T);
  68. }
  69. private:
  70. static constexpr U64 GC_MASK = 1ul << 63ul;
  71. I64 m_sig = 0; ///< Signature to identify the user data.
  72. /// Encodes an address and a flag for garbage collection.
  73. /// High bit is the GC flag and the rest are an address.
  74. U64 m_addressAndGarbageCollect = 0;
  75. };
  76. /// Lua binder class. A wrapper on top of LUA
  77. class LuaBinder
  78. {
  79. public:
  80. template<typename T>
  81. using Allocator = ChainAllocator<T>;
  82. LuaBinder();
  83. ~LuaBinder();
  84. ANKI_USE_RESULT Error create(Allocator<U8>& alloc, void* parent);
  85. lua_State* getLuaState()
  86. {
  87. return m_l;
  88. }
  89. Allocator<U8> getAllocator() const
  90. {
  91. return m_alloc;
  92. }
  93. void* getParent() const
  94. {
  95. return m_parent;
  96. }
  97. /// Expose a variable to the lua state
  98. template<typename T>
  99. void exposeVariable(const char* name, T* y);
  100. /// Evaluate a string
  101. ANKI_USE_RESULT Error evalString(const CString& str);
  102. /// For debugging purposes
  103. static void stackDump(lua_State* l);
  104. /// Make sure that the arguments match the argsCount number
  105. static void checkArgsCount(lua_State* l, I argsCount);
  106. /// Create a new LUA class
  107. static void createClass(lua_State* l, const char* className);
  108. /// Add new function in a class that it's already in the stack
  109. static void pushLuaCFuncMethod(lua_State* l, const char* name,
  110. lua_CFunction luafunc);
  111. /// Add a new static function in the class.
  112. static void pushLuaCFuncStaticMethod(lua_State* l, const char* className,
  113. const char* name, lua_CFunction luafunc);
  114. /// Add a new function.
  115. static void pushLuaCFunc(
  116. lua_State* l, const char* name, lua_CFunction luafunc);
  117. /// Get a number from the stack.
  118. template<typename TNumber>
  119. static ANKI_USE_RESULT Error checkNumber(
  120. lua_State* l, I stackIdx, TNumber& number);
  121. /// Get a string from the stack.
  122. static ANKI_USE_RESULT Error checkString(
  123. lua_State* l, I32 stackIdx, const char*& out);
  124. /// Get some user data from the stack.
  125. /// The function uses the type signature to validate the type and not the
  126. /// typeName. That is supposed to be faster.
  127. static ANKI_USE_RESULT Error checkUserData(
  128. lua_State* l, I32 stackIdx, const char* typeName, I64 typeSignature,
  129. UserData*& out);
  130. /// Allocate memory.
  131. static void* luaAlloc(lua_State* l, size_t size, U32 alignment);
  132. /// Free memory.
  133. static void luaFree(lua_State* l, void* ptr);
  134. template<typename TWrapedType>
  135. static I64 getWrappedTypeSignature();
  136. template<typename TWrapedType>
  137. static const char* getWrappedTypeName();
  138. private:
  139. Allocator<U8> m_alloc;
  140. lua_State* m_l = nullptr;
  141. void* m_parent = nullptr; ///< Point to the ScriptManager
  142. static void* luaAllocCallback(
  143. void* userData, void* ptr, PtrSize osize, PtrSize nsize);
  144. static ANKI_USE_RESULT Error checkNumberInternal(
  145. lua_State* l, I32 stackIdx, lua_Number& number);
  146. };
  147. //==============================================================================
  148. template<typename TNumber>
  149. inline Error LuaBinder::checkNumber(
  150. lua_State* l, I stackIdx, TNumber& number)
  151. {
  152. lua_Number lnum;
  153. Error err = checkNumberInternal(l, stackIdx, lnum);
  154. if(!err)
  155. {
  156. number = lnum;
  157. }
  158. return err;
  159. }
  160. //==============================================================================
  161. template<typename T>
  162. inline void LuaBinder::exposeVariable(const char* name, T* y)
  163. {
  164. void* ptr = lua_newuserdata(m_l, sizeof(UserData));
  165. UserData* ud = static_cast<UserData*>(ptr);
  166. ud->initPointed(getWrappedTypeSignature<T>(), y);
  167. luaL_setmetatable(m_l, getWrappedTypeName<T>());
  168. lua_setglobal(m_l, name);
  169. }
  170. } // end namespace anki