UpValue.cs 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. using System.Runtime.CompilerServices;
  2. namespace Lua.Runtime;
  3. public sealed class UpValue
  4. {
  5. LuaValue value;
  6. public LuaThread Thread { get; }
  7. public bool IsClosed { get; private set; }
  8. public int RegisterIndex { get; private set; }
  9. UpValue(LuaThread thread)
  10. {
  11. Thread = thread;
  12. }
  13. public static UpValue Open(LuaThread thread, int registerIndex)
  14. {
  15. return new(thread)
  16. {
  17. RegisterIndex = registerIndex
  18. };
  19. }
  20. public static UpValue Closed(LuaThread thread, LuaValue value)
  21. {
  22. return new(thread)
  23. {
  24. IsClosed = true,
  25. value = value
  26. };
  27. }
  28. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  29. public LuaValue GetValue()
  30. {
  31. if (IsClosed)
  32. {
  33. return value;
  34. }
  35. else
  36. {
  37. return Thread.Stack.UnsafeGet(RegisterIndex);
  38. }
  39. }
  40. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  41. public void SetValue(LuaValue value)
  42. {
  43. if (IsClosed)
  44. {
  45. this.value = value;
  46. }
  47. else
  48. {
  49. Thread.Stack.UnsafeGet(RegisterIndex) = value;
  50. }
  51. }
  52. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  53. public void Close()
  54. {
  55. if (!IsClosed)
  56. {
  57. value = Thread.Stack.UnsafeGet(RegisterIndex);
  58. }
  59. IsClosed = true;
  60. }
  61. }