BasicModule.cs 10 KB

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