Skip to content

Commit 8491631

Browse files
committed
Add Lua.GetGlobalOrDefault()
1 parent eceeb8f commit 8491631

File tree

1 file changed

+34
-1
lines changed

1 file changed

+34
-1
lines changed

src/Laylua/Library/Lua.cs

Lines changed: 34 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
using System;
1+
using System;
22
using System.Collections.Generic;
33
using System.Diagnostics;
44
using System.Diagnostics.CodeAnalysis;
@@ -297,6 +297,39 @@ public TValue GetGlobal<TValue>(ReadOnlySpan<char> name)
297297
}
298298
}
299299

300+
/// <inheritdoc cref="LuaReference._reference"/>
301+
/// <summary>
302+
/// Gets the value of a global variable.
303+
/// </summary>
304+
/// <param name="name"> The name of the global variable. </param>
305+
/// <typeparam name="TValue"> The type of the value. </typeparam>
306+
/// <returns>
307+
/// The value of the global variable or <see langword="default"/>.
308+
/// </returns>
309+
[MethodImpl(MethodImplOptions.NoInlining)]
310+
public TValue? GetGlobalOrDefault<TValue>(ReadOnlySpan<char> name)
311+
where TValue : notnull
312+
{
313+
return TryGetGlobal<TValue>(name, out var value) ? value : default;
314+
}
315+
316+
/// <inheritdoc cref="LuaReference._reference"/>
317+
/// <summary>
318+
/// Gets the value of a global variable.
319+
/// </summary>
320+
/// <param name="name"> The name of the global variable. </param>
321+
/// <param name="defaultValue"> The default value to return. </param>
322+
/// <typeparam name="TValue"> The type of the value. </typeparam>
323+
/// <returns>
324+
/// The value from the table or <paramref name="defaultValue"/>.
325+
/// </returns>
326+
[MethodImpl(MethodImplOptions.NoInlining)]
327+
public TValue? GetGlobalOrDefault<TValue>(ReadOnlySpan<char> name, TValue defaultValue)
328+
where TValue : notnull
329+
{
330+
return TryGetGlobal<TValue>(name, out var value) ? value : defaultValue;
331+
}
332+
300333
/// <summary>
301334
/// Sets the value of a global variable.
302335
/// </summary>

0 commit comments

Comments
 (0)