BasicLibrary.cs 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570
  1. using System.Globalization;
  2. using Lua.Internal;
  3. using Lua.Runtime;
  4. namespace Lua.Standard;
  5. public sealed class BasicLibrary
  6. {
  7. public static readonly BasicLibrary Instance = new();
  8. public BasicLibrary()
  9. {
  10. Functions =
  11. [
  12. new("assert", Assert),
  13. new("collectgarbage", CollectGarbage),
  14. new("dofile", DoFile),
  15. new("error", Error),
  16. new("getmetatable", GetMetatable),
  17. new("ipairs", IPairs),
  18. new("loadfile", LoadFile),
  19. new("load", Load),
  20. new("next", Next),
  21. new("pairs", Pairs),
  22. new("pcall", PCall),
  23. new("print", Print),
  24. new("rawequal", RawEqual),
  25. new("rawget", RawGet),
  26. new("rawlen", RawLen),
  27. new("rawset", RawSet),
  28. new("select", Select),
  29. new("setmetatable", SetMetatable),
  30. new("tonumber", ToNumber),
  31. new("tostring", ToString),
  32. new("type", Type),
  33. new("xpcall", XPCall),
  34. ];
  35. IPairsIterator = new("iterator", (context, cancellationToken) =>
  36. {
  37. var table = context.GetArgument<LuaTable>(0);
  38. var i = context.GetArgument<double>(1);
  39. i++;
  40. if (table.TryGetValue(i, out var value))
  41. {
  42. return new(context.Return(i, value));
  43. }
  44. else
  45. {
  46. return new(context.Return(LuaValue.Nil, LuaValue.Nil));
  47. }
  48. });
  49. PairsIterator = new("iterator", Next);
  50. }
  51. public readonly LuaFunction[] Functions;
  52. readonly LuaFunction IPairsIterator;
  53. readonly LuaFunction PairsIterator;
  54. public ValueTask<int> Assert(LuaFunctionExecutionContext context, CancellationToken cancellationToken)
  55. {
  56. var arg0 = context.GetArgument(0);
  57. if (!arg0.ToBoolean())
  58. {
  59. var message = "assertion failed!";
  60. if (context.HasArgument(1))
  61. {
  62. message = context.GetArgument<string>(1);
  63. }
  64. throw new LuaAssertionException(context.Thread, message);
  65. }
  66. return new(context.Return(context.Arguments));
  67. }
  68. public ValueTask<int> CollectGarbage(LuaFunctionExecutionContext context, CancellationToken cancellationToken)
  69. {
  70. GC.Collect();
  71. return new(context.Return());
  72. }
  73. public async ValueTask<int> DoFile(LuaFunctionExecutionContext context, CancellationToken cancellationToken)
  74. {
  75. var arg0 = context.GetArgument<string>(0);
  76. // do not use LuaState.DoFileAsync as it uses the newExecutionContext
  77. var bytes = await File.ReadAllBytesAsync(arg0, cancellationToken);
  78. var fileName = "@" + arg0;
  79. return await context.State.Load(bytes, fileName).InvokeAsync(context with { ArgumentCount = context.ArgumentCount - 1 }, cancellationToken);
  80. }
  81. public ValueTask<int> Error(LuaFunctionExecutionContext context, CancellationToken cancellationToken)
  82. {
  83. var value = context.ArgumentCount == 0
  84. ? LuaValue.Nil
  85. : context.Arguments[0];
  86. throw new LuaRuntimeException(context.Thread, value);
  87. }
  88. public ValueTask<int> GetMetatable(LuaFunctionExecutionContext context, CancellationToken cancellationToken)
  89. {
  90. var arg0 = context.GetArgument(0);
  91. if (context.State.TryGetMetatable(arg0, out var metatable))
  92. {
  93. if (metatable.TryGetValue(Metamethods.Metatable, out var metaMetatable))
  94. {
  95. context.Return(metaMetatable);
  96. }
  97. else
  98. {
  99. context.Return(metatable);
  100. }
  101. }
  102. else
  103. {
  104. context.Return(LuaValue.Nil);
  105. }
  106. return default;
  107. }
  108. public ValueTask<int> IPairs(LuaFunctionExecutionContext context, CancellationToken cancellationToken)
  109. {
  110. var arg0 = context.GetArgument<LuaTable>(0);
  111. // If table has a metamethod __ipairs, calls it with table as argument and returns the first three results from the call.
  112. if (arg0.Metatable != null && arg0.Metatable.TryGetValue(Metamethods.IPairs, out var metamethod))
  113. {
  114. if (!metamethod.TryRead<LuaFunction>(out var function))
  115. {
  116. LuaRuntimeException.AttemptInvalidOperation(context.Thread, "call", metamethod);
  117. }
  118. return function.InvokeAsync(context, cancellationToken);
  119. }
  120. return new(context.Return(IPairsIterator, arg0, 0));
  121. }
  122. public async ValueTask<int> LoadFile(LuaFunctionExecutionContext context, CancellationToken cancellationToken)
  123. {
  124. var arg0 = context.GetArgument<string>(0);
  125. var mode = context.HasArgument(1)
  126. ? context.GetArgument<string>(1)
  127. : "bt";
  128. var arg2 = context.HasArgument(2)
  129. ? context.GetArgument<LuaTable>(2)
  130. : null;
  131. // do not use LuaState.DoFileAsync as it uses the newExecutionContext
  132. try
  133. {
  134. var bytes = await File.ReadAllBytesAsync(arg0, cancellationToken);
  135. var fileName = "@" + arg0;
  136. return context.Return(context.State.Load(bytes, fileName, mode, arg2));
  137. }
  138. catch (Exception ex)
  139. {
  140. return context.Return(LuaValue.Nil, ex.Message);
  141. }
  142. }
  143. public ValueTask<int> Load(LuaFunctionExecutionContext context, CancellationToken cancellationToken)
  144. {
  145. // Lua-CSharp does not support binary chunks, the mode argument is ignored.
  146. var arg0 = context.GetArgument(0);
  147. var name = context.HasArgument(1)
  148. ? context.GetArgument<string>(1)
  149. : null;
  150. var mode = context.HasArgument(2)
  151. ? context.GetArgument<string>(2)
  152. : "bt";
  153. var arg3 = context.HasArgument(3)
  154. ? context.GetArgument<LuaTable>(3)
  155. : context.State.Environment;
  156. // do not use LuaState.DoFileAsync as it uses the newExecutionContext
  157. try
  158. {
  159. if (arg0.TryRead<string>(out var str))
  160. {
  161. return new(context.Return(context.State.Load(str, name ?? str, arg3)));
  162. }
  163. else if (arg0.TryRead<LuaFunction>(out var function))
  164. {
  165. // TODO:
  166. throw new NotImplementedException();
  167. }
  168. else
  169. {
  170. LuaRuntimeException.BadArgument(context.Thread, 1, "load");
  171. return default; // dummy
  172. }
  173. }
  174. catch (Exception ex)
  175. {
  176. return new(context.Return(LuaValue.Nil, ex.Message));
  177. }
  178. }
  179. public ValueTask<int> Next(LuaFunctionExecutionContext context, CancellationToken cancellationToken)
  180. {
  181. var arg0 = context.GetArgument<LuaTable>(0);
  182. var arg1 = context.HasArgument(1) ? context.Arguments[1] : LuaValue.Nil;
  183. if (arg0.TryGetNext(arg1, out var kv))
  184. {
  185. return new(context.Return(kv.Key, kv.Value));
  186. }
  187. else
  188. {
  189. return new(context.Return(LuaValue.Nil));
  190. }
  191. }
  192. public ValueTask<int> Pairs(LuaFunctionExecutionContext context, CancellationToken cancellationToken)
  193. {
  194. var arg0 = context.GetArgument<LuaTable>(0);
  195. // If table has a metamethod __pairs, calls it with table as argument and returns the first three results from the call.
  196. if (arg0.Metatable != null && arg0.Metatable.TryGetValue(Metamethods.Pairs, out var metamethod))
  197. {
  198. if (!metamethod.TryRead<LuaFunction>(out var function))
  199. {
  200. LuaRuntimeException.AttemptInvalidOperation(context.Thread, "call", metamethod);
  201. }
  202. return function.InvokeAsync(context, cancellationToken);
  203. }
  204. return new(context.Return(PairsIterator, arg0, LuaValue.Nil));
  205. }
  206. public async ValueTask<int> PCall(LuaFunctionExecutionContext context, CancellationToken cancellationToken)
  207. {
  208. var frameCount = context.Thread.CallStack.Count;
  209. var arg0 = context.GetArgument<LuaFunction>(0);
  210. try
  211. {
  212. var count = await arg0.InvokeAsync(context with { ArgumentCount = context.ArgumentCount - 1, ReturnFrameBase = context.ReturnFrameBase + 1 }, cancellationToken);
  213. context.Thread.Stack.Get(context.ReturnFrameBase) = true;
  214. return count + 1;
  215. }
  216. catch (Exception ex)
  217. {
  218. context.Thread.CallStack.PopUntil(frameCount);
  219. if (ex is LuaRuntimeException luaEx)
  220. {
  221. return context.Return(false, luaEx.ErrorObject);
  222. }
  223. else
  224. {
  225. return context.Return(false, ex.Message);
  226. }
  227. }
  228. }
  229. public async ValueTask<int> Print(LuaFunctionExecutionContext context, CancellationToken cancellationToken)
  230. {
  231. for (int i = 0; i < context.ArgumentCount; i++)
  232. {
  233. await context.Arguments[i].CallToStringAsync(context, cancellationToken);
  234. Console.Write(context.Thread.Stack.Pop().Read<string>());
  235. Console.Write('\t');
  236. }
  237. Console.WriteLine();
  238. return context.Return();
  239. }
  240. public ValueTask<int> RawEqual(LuaFunctionExecutionContext context, CancellationToken cancellationToken)
  241. {
  242. var arg0 = context.GetArgument(0);
  243. var arg1 = context.GetArgument(1);
  244. return new(context.Return(arg0 == arg1));
  245. }
  246. public ValueTask<int> RawGet(LuaFunctionExecutionContext context, CancellationToken cancellationToken)
  247. {
  248. var arg0 = context.GetArgument<LuaTable>(0);
  249. var arg1 = context.GetArgument(1);
  250. return new(context.Return(arg0[arg1]));
  251. }
  252. public ValueTask<int> RawLen(LuaFunctionExecutionContext context, CancellationToken cancellationToken)
  253. {
  254. var arg0 = context.GetArgument(0);
  255. if (arg0.TryRead<LuaTable>(out var table))
  256. {
  257. return new(context.Return(table.ArrayLength));
  258. }
  259. else if (arg0.TryRead<string>(out var str))
  260. {
  261. return new(context.Return(str.Length));
  262. }
  263. else
  264. {
  265. LuaRuntimeException.BadArgument(context.Thread, 2, "rawlen", [LuaValueType.String, LuaValueType.Table]);
  266. return default;
  267. }
  268. }
  269. public ValueTask<int> RawSet(LuaFunctionExecutionContext context, CancellationToken cancellationToken)
  270. {
  271. var arg0 = context.GetArgument<LuaTable>(0);
  272. var arg1 = context.GetArgument(1);
  273. var arg2 = context.GetArgument(2);
  274. arg0[arg1] = arg2;
  275. return new(context.Return());
  276. }
  277. public ValueTask<int> Select(LuaFunctionExecutionContext context, CancellationToken cancellationToken)
  278. {
  279. var arg0 = context.GetArgument(0);
  280. if (arg0.TryRead<int>(out var index))
  281. {
  282. if (Math.Abs(index) > context.ArgumentCount)
  283. {
  284. throw new LuaRuntimeException(context.Thread, "bad argument #1 to 'select' (index out of range)");
  285. }
  286. var span = index >= 0
  287. ? context.Arguments[index..]
  288. : context.Arguments[(context.ArgumentCount + index)..];
  289. return new(context.Return(span));
  290. }
  291. else if (arg0.TryRead<string>(out var str) && str == "#")
  292. {
  293. return new(context.Return(context.ArgumentCount - 1));
  294. }
  295. else
  296. {
  297. LuaRuntimeException.BadArgument(context.Thread, 1, "select", "number", arg0.Type.ToString());
  298. return default;
  299. }
  300. }
  301. public ValueTask<int> SetMetatable(LuaFunctionExecutionContext context, CancellationToken cancellationToken)
  302. {
  303. var arg0 = context.GetArgument<LuaTable>(0);
  304. var arg1 = context.GetArgument(1);
  305. if (arg1.Type is not (LuaValueType.Nil or LuaValueType.Table))
  306. {
  307. LuaRuntimeException.BadArgument(context.Thread, 2, "setmetatable", [LuaValueType.Nil, LuaValueType.Table]);
  308. }
  309. if (arg0.Metatable != null && arg0.Metatable.TryGetValue(Metamethods.Metatable, out _))
  310. {
  311. throw new LuaRuntimeException(context.Thread, "cannot change a protected metatable");
  312. }
  313. else if (arg1.Type is LuaValueType.Nil)
  314. {
  315. arg0.Metatable = null;
  316. }
  317. else
  318. {
  319. arg0.Metatable = arg1.Read<LuaTable>();
  320. }
  321. return new(context.Return(arg0));
  322. }
  323. public ValueTask<int> ToNumber(LuaFunctionExecutionContext context, CancellationToken cancellationToken)
  324. {
  325. var e = context.GetArgument(0);
  326. int? toBase = context.HasArgument(1)
  327. ? (int)context.GetArgument<double>(1)
  328. : null;
  329. if (toBase != null && (toBase < 2 || toBase > 36))
  330. {
  331. throw new LuaRuntimeException(context.Thread, "bad argument #2 to 'tonumber' (base out of range)");
  332. }
  333. double? value = null;
  334. if (e.Type is LuaValueType.Number)
  335. {
  336. value = e.UnsafeRead<double>();
  337. }
  338. else if (e.TryRead<string>(out var str))
  339. {
  340. if (toBase == null)
  341. {
  342. if (e.TryRead<double>(out var result))
  343. {
  344. value = result;
  345. }
  346. }
  347. else if (toBase == 10)
  348. {
  349. if (double.TryParse(str, NumberStyles.Float, CultureInfo.InvariantCulture, out var result))
  350. {
  351. value = result;
  352. }
  353. }
  354. else
  355. {
  356. try
  357. {
  358. // if the base is not 10, str cannot contain a minus sign
  359. var span = str.AsSpan().Trim();
  360. if (span.Length == 0) goto END;
  361. var first = span[0];
  362. var sign = first == '-' ? -1 : 1;
  363. if (first is '+' or '-')
  364. {
  365. span = span[1..];
  366. }
  367. if (span.Length == 0) goto END;
  368. if (toBase == 16 && span.Length > 2 && span[0] is '0' && span[1] is 'x' or 'X')
  369. {
  370. value = sign * HexConverter.ToDouble(span);
  371. }
  372. else
  373. {
  374. value = sign * StringToDouble(span, toBase.Value);
  375. }
  376. }
  377. catch (FormatException)
  378. {
  379. goto END;
  380. }
  381. }
  382. }
  383. else
  384. {
  385. goto END;
  386. }
  387. END:
  388. if (value is double.NaN)
  389. {
  390. value = null;
  391. }
  392. return new(context.Return(value ?? LuaValue.Nil));
  393. }
  394. static double StringToDouble(ReadOnlySpan<char> text, int toBase)
  395. {
  396. var value = 0.0;
  397. for (int i = 0; i < text.Length; i++)
  398. {
  399. var v = text[i] switch
  400. {
  401. '0' => 0,
  402. '1' => 1,
  403. '2' => 2,
  404. '3' => 3,
  405. '4' => 4,
  406. '5' => 5,
  407. '6' => 6,
  408. '7' => 7,
  409. '8' => 8,
  410. '9' => 9,
  411. 'a' or 'A' => 10,
  412. 'b' or 'B' => 11,
  413. 'c' or 'C' => 12,
  414. 'd' or 'D' => 13,
  415. 'e' or 'E' => 14,
  416. 'f' or 'F' => 15,
  417. 'g' or 'G' => 16,
  418. 'h' or 'H' => 17,
  419. 'i' or 'I' => 18,
  420. 'j' or 'J' => 19,
  421. 'k' or 'K' => 20,
  422. 'l' or 'L' => 21,
  423. 'm' or 'M' => 22,
  424. 'n' or 'N' => 23,
  425. 'o' or 'O' => 24,
  426. 'p' or 'P' => 25,
  427. 'q' or 'Q' => 26,
  428. 'r' or 'R' => 27,
  429. 's' or 'S' => 28,
  430. 't' or 'T' => 29,
  431. 'u' or 'U' => 30,
  432. 'v' or 'V' => 31,
  433. 'w' or 'W' => 32,
  434. 'x' or 'X' => 33,
  435. 'y' or 'Y' => 34,
  436. 'z' or 'Z' => 35,
  437. _ => 0,
  438. };
  439. if (v >= toBase)
  440. {
  441. throw new FormatException();
  442. }
  443. value += v * Math.Pow(toBase, text.Length - i - 1);
  444. }
  445. return value;
  446. }
  447. public ValueTask<int> ToString(LuaFunctionExecutionContext context, CancellationToken cancellationToken)
  448. {
  449. var arg0 = context.GetArgument(0);
  450. context.Return();
  451. return arg0.CallToStringAsync(context, cancellationToken);
  452. }
  453. public ValueTask<int> Type(LuaFunctionExecutionContext context, CancellationToken cancellationToken)
  454. {
  455. var arg0 = context.GetArgument(0);
  456. return new(context.Return(arg0.Type switch
  457. {
  458. LuaValueType.Nil => "nil",
  459. LuaValueType.Boolean => "boolean",
  460. LuaValueType.String => "string",
  461. LuaValueType.Number => "number",
  462. LuaValueType.Function => "function",
  463. LuaValueType.Thread => "thread",
  464. LuaValueType.LightUserData => "userdata",
  465. LuaValueType.UserData => "userdata",
  466. LuaValueType.Table => "table",
  467. _ => throw new NotImplementedException(),
  468. }));
  469. }
  470. public async ValueTask<int> XPCall(LuaFunctionExecutionContext context, CancellationToken cancellationToken)
  471. {
  472. var frameCount = context.Thread.CallStack.Count;
  473. var arg0 = context.GetArgument<LuaFunction>(0);
  474. var arg1 = context.GetArgument<LuaFunction>(1);
  475. try
  476. {
  477. var count = await arg0.InvokeAsync(context with { ArgumentCount = context.ArgumentCount - 2, ReturnFrameBase = context.ReturnFrameBase + 1 }, cancellationToken);
  478. context.Thread.Stack.Get(context.ReturnFrameBase) = true;
  479. return count + 1;
  480. }
  481. catch (Exception ex)
  482. {
  483. context.Thread.CallStack.PopUntil(frameCount);
  484. var error = ex is LuaRuntimeException luaEx ? luaEx.ErrorObject : ex.Message;
  485. context.Thread.Push(error);
  486. // invoke error handler
  487. var count = await arg1.InvokeAsync(context with { ArgumentCount = 1, ReturnFrameBase = context.ReturnFrameBase + 1 }, cancellationToken);
  488. context.Thread.Stack.Get(context.ReturnFrameBase) = false;
  489. return count + 1;
  490. }
  491. }
  492. }