|
| 1 | +using System; |
| 2 | +using System.Globalization; |
| 3 | +using Qommon; |
| 4 | + |
| 5 | +namespace Laylua.Moon; |
| 6 | + |
| 7 | +internal sealed unsafe class LuaMainState : LuaState |
| 8 | +{ |
| 9 | + public override LuaAllocator? Allocator { get; } |
| 10 | + |
| 11 | + public override LuaGC GC { get; } |
| 12 | + |
| 13 | + protected override lua_State* LCore => _L; |
| 14 | + |
| 15 | + internal object? State |
| 16 | + { |
| 17 | + get => _layluaState.State; |
| 18 | + set => _layluaState.State = value; |
| 19 | + } |
| 20 | + |
| 21 | + private LuaAllocFunction? _safeAllocFunction; |
| 22 | + |
| 23 | + private LayluaState _layluaState = null!; |
| 24 | + private lua_State* _L; |
| 25 | + |
| 26 | + internal LuaMainState(LuaAllocator? allocator) |
| 27 | + { |
| 28 | + if (allocator == null) |
| 29 | + { |
| 30 | + _L = luaL_newstate(); |
| 31 | + } |
| 32 | + else |
| 33 | + { |
| 34 | + _L = lua_newstate(WrapAllocFunction(allocator), null); |
| 35 | + Allocator = allocator; |
| 36 | + } |
| 37 | + |
| 38 | + ValidateNewState(); |
| 39 | + InitializeLayluaState(); |
| 40 | + |
| 41 | + GC = new(this); |
| 42 | + } |
| 43 | + |
| 44 | + private void ValidateNewState() |
| 45 | + { |
| 46 | + if (_L == null) |
| 47 | + { |
| 48 | + Throw.InvalidOperationException("Failed to create a new Lua state."); |
| 49 | + } |
| 50 | + |
| 51 | + var version = lua_version(_L).ToString(CultureInfo.InvariantCulture); |
| 52 | + if (version.Length != 3 || version[0] != LuaVersionMajor[0] || version[2] != LuaVersionMinor[0]) |
| 53 | + { |
| 54 | + Throw.InvalidOperationException($"Invalid Lua version loaded. Expected '{LuaVersion}'."); |
| 55 | + } |
| 56 | + } |
| 57 | + |
| 58 | + private void InitializeLayluaState() |
| 59 | + { |
| 60 | + if (!LayluaState.TryFromExtraSpace(_L, out var state)) |
| 61 | + { |
| 62 | + var panicPtr = LayluaNative.InitializePanic(); |
| 63 | + state = LayluaState.Create(panicPtr); |
| 64 | + *(IntPtr*) lua_getextraspace(_L) = state.GCPtr; |
| 65 | + lua_atpanic(_L, (delegate* unmanaged[Cdecl]<lua_State*, int>) panicPtr); |
| 66 | + } |
| 67 | + |
| 68 | + _layluaState = state; |
| 69 | + } |
| 70 | + |
| 71 | + internal LuaAllocFunction WrapAllocFunction(LuaAllocator allocator) |
| 72 | + { |
| 73 | + Guard.IsNotNull(allocator); |
| 74 | + |
| 75 | + _safeAllocFunction = (_, ptr, osize, nsize) => |
| 76 | + { |
| 77 | + return allocator.Allocate(ptr, osize, nsize); |
| 78 | + }; |
| 79 | + |
| 80 | + return _safeAllocFunction; |
| 81 | + } |
| 82 | + |
| 83 | + internal override void Close() |
| 84 | + { |
| 85 | + if (_L == null) |
| 86 | + return; |
| 87 | + |
| 88 | + lua_close(_L); |
| 89 | + _layluaState.Dispose(); |
| 90 | + _L = null; |
| 91 | + } |
| 92 | +} |
0 commit comments