Skip to content

Commit f049b75

Browse files
committed
Add: TimeLibrary
1 parent 86ae57a commit f049b75

File tree

2 files changed

+41
-17
lines changed

2 files changed

+41
-17
lines changed

src/Lua.Unity/Assets/Lua.Unity/Runtime/LuaStateExtensions.cs

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -27,6 +27,12 @@ public static void OpenUnityLibraries(this LuaState state)
2727
}
2828
color.Metatable = ColorLibrary.Instance.Metatable;
2929
state.Environment["color"] = color;
30+
31+
var time = new LuaTable
32+
{
33+
Metatable = TimeLibrary.Instance.Metatable
34+
};
35+
state.Environment["time"] = time;
3036
}
3137
}
3238
}
Lines changed: 35 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,4 @@
1-
using System;
2-
using System.Threading;
3-
using System.Threading.Tasks;
1+
using Lua.Runtime;
42
using UnityEngine;
53

64
namespace Lua.Unity
@@ -9,23 +7,43 @@ public sealed class TimeLibrary
97
{
108
public static readonly TimeLibrary Instance = new();
119

12-
public readonly LuaFunction[] functions = new LuaFunction[]
13-
{
14-
new("time", GetTime),
15-
new("delta_time", GetDeltaTime),
16-
};
10+
public readonly LuaTable Metatable = new();
1711

18-
public static ValueTask<int> GetTime(LuaFunctionExecutionContext context, Memory<LuaValue> buffer, CancellationToken cancellationToken)
12+
public TimeLibrary()
1913
{
20-
buffer.Span[0] = Time.timeAsDouble;
21-
return new(1);
22-
}
14+
Metatable[Metamethods.Index] = new LuaFunction((context, buffer, ct) =>
15+
{
16+
var name = context.GetArgument<string>(1);
17+
buffer.Span[0] = name switch
18+
{
19+
"time" => Time.timeAsDouble,
20+
"unscaled_time" => Time.unscaledTimeAsDouble,
21+
"delta_time" => Time.deltaTime,
22+
"unscaled_delta_time" => Time.unscaledDeltaTime,
23+
"fixed_time" => Time.fixedTimeAsDouble,
24+
"fixed_unscaled_time" => Time.fixedUnscaledTimeAsDouble,
25+
"fixed_delta_time" => Time.fixedDeltaTime,
26+
"fixed_unscaled_delta_time" => Time.fixedUnscaledDeltaTime,
27+
"time_since_level_load" => Time.timeSinceLevelLoadAsDouble,
28+
"in_fixed_time_step" => Time.inFixedTimeStep,
29+
"frame_count" => Time.frameCount,
30+
"time_scale" => Time.timeScale,
31+
_ => LuaValue.Nil,
32+
};
33+
return new(1);
34+
});
2335

24-
public static ValueTask<int> GetDeltaTime(LuaFunctionExecutionContext context, Memory<LuaValue> buffer, CancellationToken cancellationToken)
25-
{
26-
buffer.Span[0] = Time.deltaTime;
27-
return new(1);
36+
Metatable[Metamethods.NewIndex] = new LuaFunction((context, buffer, ct) =>
37+
{
38+
var name = context.GetArgument<string>(1);
39+
switch (name)
40+
{
41+
case "time_scale":
42+
Time.timeScale = context.GetArgument<float>(2);
43+
break;
44+
}
45+
return new(0);
46+
});
2847
}
29-
3048
}
3149
}

0 commit comments

Comments
 (0)