-
Notifications
You must be signed in to change notification settings - Fork 242
Expand file tree
/
Copy pathOsTimeModule.cs
More file actions
executable file
·289 lines (240 loc) · 6.81 KB
/
Copy pathOsTimeModule.cs
File metadata and controls
executable file
·289 lines (240 loc) · 6.81 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
// Disable warnings about XML documentation
#pragma warning disable 1591
using System;
using System.Collections.Generic;
using System.Text;
namespace MoonSharp.Interpreter.CoreLib
{
/// <summary>
/// Class implementing time related Lua functions from the 'os' module.
/// </summary>
[MoonSharpModule(Namespace = "os")]
public class OsTimeModule
{
static DateTime Time0 = DateTime.UtcNow;
static DateTime Epoch = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
private static DynValue GetUnixTime(DateTime dateTime, DateTime? epoch = null)
{
double time = (dateTime - (epoch ?? Epoch)).TotalSeconds;
if (time < 0.0)
return DynValue.Nil;
return DynValue.NewNumber(time);
}
private static DateTime FromUnixTime(double unixtime)
{
TimeSpan ts = TimeSpan.FromSeconds(unixtime);
return Epoch + ts;
}
[MoonSharpModuleMethod]
public static DynValue clock(ScriptExecutionContext executionContext, CallbackArguments args)
{
return GetUnixTime(DateTime.UtcNow, Time0);
}
[MoonSharpModuleMethod]
public static DynValue difftime(ScriptExecutionContext executionContext, CallbackArguments args)
{
DynValue t2 = args.AsType(0, "difftime", DataType.Number, false);
DynValue t1 = args.AsType(1, "difftime", DataType.Number, true);
if (t1.IsNil())
return DynValue.NewNumber(t2.Number);
return DynValue.NewNumber(t2.Number - t1.Number);
}
[MoonSharpModuleMethod]
public static DynValue time(ScriptExecutionContext executionContext, CallbackArguments args)
{
DateTime date = DateTime.UtcNow;
if (args.Count > 0)
{
DynValue vt = args.AsType(0, "time", DataType.Table, true);
if (vt.Type == DataType.Table)
date = ParseTimeTable(vt.Table);
}
return GetUnixTime(date);
}
static DateTime ParseTimeTable(Table t)
{
int sec = GetTimeTableField(t, "sec") ?? 0;
int min = GetTimeTableField(t, "min") ?? 0;
int hour = GetTimeTableField(t, "hour") ?? 12;
int? day = GetTimeTableField(t, "day");
int? month = GetTimeTableField(t, "month");
int? year = GetTimeTableField(t, "year");
if (day == null)
throw new ScriptRuntimeException("field 'day' missing in date table");
if (month == null)
throw new ScriptRuntimeException("field 'month' missing in date table");
if (year == null)
throw new ScriptRuntimeException("field 'year' missing in date table");
return new DateTime(year.Value, month.Value, day.Value, hour, min, sec);
}
private static int? GetTimeTableField(Table t, string key)
{
DynValue v = t.Get(key);
double? d = v.CastToNumber();
if (d.HasValue)
return (int)d.Value;
return null;
}
[MoonSharpModuleMethod]
public static DynValue date(ScriptExecutionContext executionContext, CallbackArguments args)
{
DateTime reference = DateTime.UtcNow;
DynValue vformat = args.AsType(0, "date", DataType.String, true);
DynValue vtime = args.AsType(1, "date", DataType.Number, true);
string format = (vformat.IsNil()) ? "%c" : vformat.String;
if (vtime.IsNotNil())
reference = FromUnixTime(vtime.Number);
bool isDst = false;
if (format.StartsWith("!"))
{
format = format.Substring(1);
}
else
{
#if !(PCL || ENABLE_DOTNET || NETFX_CORE)
try
{
TimeZoneInfo localTimeZoneInfo = executionContext.OwnerScript.Options.LocalTimeZoneInfo ?? TimeZoneInfo.Local;
reference = TimeZoneInfo.ConvertTimeFromUtc(reference, localTimeZoneInfo);
isDst = reference.IsDaylightSavingTime();
}
catch (TimeZoneNotFoundException)
{
// this catches a weird mono bug: https://bugzilla.xamarin.com/show_bug.cgi?id=11817
// however the behavior is definitely not correct. damn.
}
#endif
}
if (format == "*t")
{
Table t = new Table(executionContext.GetScript());
t.Set("year", DynValue.NewNumber(reference.Year));
t.Set("month", DynValue.NewNumber(reference.Month));
t.Set("day", DynValue.NewNumber(reference.Day));
t.Set("hour", DynValue.NewNumber(reference.Hour));
t.Set("min", DynValue.NewNumber(reference.Minute));
t.Set("sec", DynValue.NewNumber(reference.Second));
t.Set("wday", DynValue.NewNumber(((int)reference.DayOfWeek) + 1));
t.Set("yday", DynValue.NewNumber(reference.DayOfYear));
t.Set("isdst", DynValue.NewBoolean(isDst));
return DynValue.NewTable(t);
}
else return DynValue.NewString(StrFTime(format, reference));
}
private static string StrFTime(string format, DateTime d)
{
// ref: http://www.cplusplus.com/reference/ctime/strftime/
Dictionary<char, string> STANDARD_PATTERNS = new Dictionary<char, string>()
{
{ 'a', "ddd" },
{ 'A', "dddd" },
{ 'b', "MMM" },
{ 'B', "MMMM" },
{ 'c', "f" },
{ 'd', "dd" },
{ 'D', "MM/dd/yy" },
{ 'F', "yyyy-MM-dd" },
{ 'g', "yy" },
{ 'G', "yyyy" },
{ 'h', "MMM" },
{ 'H', "HH" },
{ 'I', "hh" },
{ 'm', "MM" },
{ 'M', "mm" },
{ 'p', "tt" },
{ 'r', "h:mm:ss tt" },
{ 'R', "HH:mm" },
{ 'S', "ss" },
{ 'T', "HH:mm:ss" },
{ 'y', "yy" },
{ 'Y', "yyyy" },
{ 'x', "d" },
{ 'X', "T" },
{ 'z', "zzz" },
{ 'Z', "zzz" },
};
StringBuilder sb = new StringBuilder();
bool isEscapeSequence = false;
for (int i = 0; i < format.Length; i++)
{
char c = format[i];
if (c == '%')
{
if (isEscapeSequence)
{
sb.Append('%');
isEscapeSequence = false;
}
else
isEscapeSequence = true;
continue;
}
if (!isEscapeSequence)
{
sb.Append(c);
continue;
}
if (c == 'O' || c == 'E') continue; // no modifiers
isEscapeSequence = false;
if (STANDARD_PATTERNS.ContainsKey(c))
{
sb.Append(d.ToString(STANDARD_PATTERNS[c]));
}
else if (c == 'e')
{
string s = d.ToString("%d");
if (s.Length < 2) s = " " + s;
sb.Append(s);
}
else if (c == 'n')
{
sb.Append('\n');
}
else if (c == 't')
{
sb.Append('\t');
}
else if (c == 'C')
{
sb.Append((int)(d.Year / 100));
}
else if (c == 'j')
{
sb.Append(d.DayOfYear.ToString("000"));
}
else if (c == 'u')
{
int weekDay = (int)d.DayOfWeek;
if (weekDay == 0)
weekDay = 7;
sb.Append(weekDay);
}
else if (c == 'w')
{
int weekDay = (int)d.DayOfWeek;
sb.Append(weekDay);
}
else if (c == 'U')
{
// Week number with the first Sunday as the first day of week one (00-53)
sb.Append("??");
}
else if (c == 'V')
{
// ISO 8601 week number (00-53)
sb.Append("??");
}
else if (c == 'W')
{
// Week number with the first Monday as the first day of week one (00-53)
sb.Append("??");
}
else
{
throw new ScriptRuntimeException("bad argument #1 to 'date' (invalid conversion specifier '{0}')", format);
}
}
return sb.ToString();
}
}
}