BasicModule.cs 9.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Globalization;
  4. using System.Linq;
  5. using System.Text;
  6. using MoonSharp.Interpreter.Execution;
  7. namespace MoonSharp.Interpreter.CoreLib
  8. {
  9. [MoonSharpModule]
  10. public class BasicModule
  11. {
  12. //type (v)
  13. //----------------------------------------------------------------------------------------------------------------
  14. //Returns the type of its only argument, coded as a string. The possible results of this function are "nil"
  15. //(a string, not the value nil), "number", "string", "boolean", "table", "function", "thread", and "userdata".
  16. [MoonSharpMethod]
  17. public static DynValue type(ScriptExecutionContext executionContext, CallbackArguments args)
  18. {
  19. if (args.Count < 1) throw ScriptRuntimeException.BadArgumentValueExpected(0, "type");
  20. DynValue v = args[0];
  21. return DynValue.NewString(v.Type.ToLuaTypeString());
  22. }
  23. //assert (v [, message])
  24. //----------------------------------------------------------------------------------------------------------------
  25. //Issues an error when the value of its argument v is false (i.e., nil or false);
  26. //otherwise, returns all its arguments. message is an error message; when absent, it defaults to "assertion failed!"
  27. [MoonSharpMethod]
  28. public static DynValue assert(ScriptExecutionContext executionContext, CallbackArguments args)
  29. {
  30. DynValue v = args[0];
  31. DynValue message = args[1];
  32. if (!v.CastToBool())
  33. {
  34. if (message.IsNil())
  35. throw new ScriptRuntimeException("assertion failed!") { DoNotDecorateMessage = true };
  36. else
  37. throw new ScriptRuntimeException(message.ToPrintString()) { DoNotDecorateMessage = true };
  38. }
  39. return DynValue.NewTupleNested(args.GetArray());
  40. }
  41. // collectgarbage ([opt [, arg]])
  42. // ----------------------------------------------------------------------------------------------------------------
  43. // This function is mostly a stub towards the CLR GC. If mode is nil, "collect" or "restart", a GC is forced.
  44. [MoonSharpMethod]
  45. public static DynValue collectgarbage(ScriptExecutionContext executionContext, CallbackArguments args)
  46. {
  47. DynValue opt = args[0];
  48. string mode = opt.CastToString();
  49. if (mode == null || mode == "collect" || mode == "restart")
  50. GC.Collect(2, GCCollectionMode.Forced);
  51. return DynValue.Nil;
  52. }
  53. // error (message [, level])
  54. // ----------------------------------------------------------------------------------------------------------------
  55. // Terminates the last protected function called and returns message as the error message. Function error never returns.
  56. // Usually, error adds some information about the error position at the beginning of the message.
  57. // The level argument specifies how to get the error position.
  58. // With level 1 (the default), the error position is where the error function was called.
  59. // Level 2 points the error to where the function that called error was called; and so on.
  60. // Passing a level 0 avoids the addition of error position information to the message.
  61. [MoonSharpMethod]
  62. public static DynValue error(ScriptExecutionContext executionContext, CallbackArguments args)
  63. {
  64. DynValue message = args.AsType(0, "error", DataType.String, false);
  65. throw new ScriptRuntimeException(message.String) { DoNotDecorateMessage = true };
  66. }
  67. // tostring (v)
  68. // ----------------------------------------------------------------------------------------------------------------
  69. // Receives a value of any type and converts it to a string in a reasonable format. (For complete control of how
  70. // numbers are converted, use string.format.)
  71. //
  72. // If the metatable of v has a "__tostring" field, then tostring calls the corresponding value with v as argument,
  73. // and uses the result of the call as its result.
  74. [MoonSharpMethod]
  75. public static DynValue tostring(ScriptExecutionContext executionContext, CallbackArguments args)
  76. {
  77. if (args.Count < 1) throw ScriptRuntimeException.BadArgumentValueExpected(0, "tostring");
  78. DynValue v = args[0];
  79. DynValue tail = executionContext.GetMetamethodTailCall(v, "__tostring", v);
  80. if (tail == null || tail.IsNil())
  81. return DynValue.NewString(v.ToPrintString());
  82. tail.TailCallData.Continuation = new CallbackFunction(__tostring_continuation, "__tostring");
  83. return tail;
  84. }
  85. private static DynValue __tostring_continuation(ScriptExecutionContext executionContext, CallbackArguments args)
  86. {
  87. DynValue b = args[0].ToScalar();
  88. if (b.IsNil())
  89. return b;
  90. if (b.Type != DataType.String)
  91. throw new ScriptRuntimeException("'tostring' must return a string");
  92. return b;
  93. }
  94. // select (index, ...)
  95. // -----------------------------------------------------------------------------
  96. // If index is a number, returns all arguments after argument number index; a negative number indexes from
  97. // the end (-1 is the last argument). Otherwise, index must be the string "#", and select returns the total
  98. // number of extra arguments it received.
  99. [MoonSharpMethod]
  100. public static DynValue select(ScriptExecutionContext executionContext, CallbackArguments args)
  101. {
  102. if (args[0].Type == DataType.String && args[0].String == "#")
  103. {
  104. if (args[args.Count - 1].Type == DataType.Tuple)
  105. {
  106. return DynValue.NewNumber(args.Count - 1 + args[args.Count - 1].Tuple.Length);
  107. }
  108. else
  109. {
  110. return DynValue.NewNumber(args.Count - 1);
  111. }
  112. }
  113. DynValue v_num = args.AsType(0, "select", DataType.Number, false);
  114. int num = (int)v_num.Number;
  115. List<DynValue> values = new List<DynValue>();
  116. if (num > 0)
  117. {
  118. for (int i = num; i < args.Count; i++)
  119. values.Add(args[i]);
  120. }
  121. else if (num < 0)
  122. {
  123. num = args.Count + num;
  124. if (num < 1)
  125. throw ScriptRuntimeException.IndexOutOfRange("select", 1);
  126. for (int i = num; i < args.Count; i++)
  127. values.Add(args[i]);
  128. }
  129. else
  130. {
  131. throw ScriptRuntimeException.IndexOutOfRange("select", 1);
  132. }
  133. return DynValue.NewTupleNested(values.ToArray());
  134. }
  135. // tonumber (e [, base])
  136. // ----------------------------------------------------------------------------------------------------------------
  137. // When called with no base, tonumber tries to convert its argument to a number. If the argument is already
  138. // a number or a string convertible to a number (see §3.4.2), then tonumber returns this number; otherwise,
  139. // it returns nil.
  140. //
  141. // When called with base, then e should be a string to be interpreted as an integer numeral in that base.
  142. // The base may be any integer between 2 and 36, inclusive. In bases above 10, the letter 'A' (in either
  143. // upper or lower case) represents 10, 'B' represents 11, and so forth, with 'Z' representing 35. If the
  144. // string e is not a valid numeral in the given base, the function returns nil.
  145. [MoonSharpMethod]
  146. public static DynValue tonumber(ScriptExecutionContext executionContext, CallbackArguments args)
  147. {
  148. if (args.Count < 1) throw ScriptRuntimeException.BadArgumentValueExpected(0, "tonumber");
  149. DynValue e = args[0];
  150. DynValue b = args.AsType(1, "tonumber", DataType.Number, true);
  151. if (b.IsNil())
  152. {
  153. if (e.Type == DataType.Number)
  154. return e;
  155. if (e.Type != DataType.String)
  156. return DynValue.Nil;
  157. double d;
  158. if (double.TryParse(e.String, NumberStyles.Any, CultureInfo.InvariantCulture, out d))
  159. {
  160. return DynValue.NewNumber(d);
  161. }
  162. return DynValue.Nil;
  163. }
  164. else
  165. {
  166. //!COMPAT: tonumber supports only 2,8,10 or 16 as base
  167. //UPDATE: added support for 3-9 base numbers
  168. DynValue ee;
  169. if (args[0].Type != DataType.Number)
  170. ee = args.AsType(0, "tonumber", DataType.String, false);
  171. else
  172. ee = DynValue.NewString(args[0].Number.ToString(CultureInfo.InvariantCulture)); ;
  173. int bb = (int)b.Number;
  174. uint uiv = 0;
  175. if (bb == 2 || bb == 8 || bb == 10 || bb == 16)
  176. {
  177. uiv = Convert.ToUInt32(ee.String.Trim(), bb);
  178. }
  179. else if (bb < 10 && bb > 2) // Support for 3, 4, 5, 6, 7 and 9 based numbers
  180. {
  181. foreach (char digit in ee.String.Trim())
  182. {
  183. int value = digit - 48;
  184. if (value < 0 || value >= bb)
  185. {
  186. throw new ScriptRuntimeException("bad argument #1 to 'tonumber' (invalid character)");
  187. }
  188. uiv = (uint)(uiv * bb) + (uint)value;
  189. }
  190. }
  191. else
  192. {
  193. throw new ScriptRuntimeException("bad argument #2 to 'tonumber' (base out of range)");
  194. }
  195. return DynValue.NewNumber(uiv);
  196. }
  197. }
  198. [MoonSharpMethod]
  199. public static DynValue print(ScriptExecutionContext executionContext, CallbackArguments args)
  200. {
  201. StringBuilder sb = new StringBuilder();
  202. for (int i = 0; i < args.Count; i++)
  203. {
  204. if (args[i].IsVoid())
  205. break;
  206. if (i != 0)
  207. sb.Append('\t');
  208. sb.Append(args.AsStringUsingMeta(executionContext, i, "print"));
  209. }
  210. executionContext.GetScript().Options.DebugPrint(sb.ToString());
  211. return DynValue.Nil;
  212. }
  213. }
  214. }