BasicMethods.cs 8.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235
  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 BasicMethods
  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!");
  36. else
  37. throw new ScriptRuntimeException(message.ToPrintString());
  38. }
  39. return DynValue.NewTupleNested(args.ToArray());
  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);
  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);
  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. return DynValue.NewNumber(args.Count - 1);
  104. DynValue v_num = args.AsType(0, "select", DataType.Number, false);
  105. int num = (int)v_num.Number;
  106. List<DynValue> values = new List<DynValue>();
  107. if (num > 0)
  108. {
  109. for (int i = num; i < args.Count; i++)
  110. values.Add(args[i]);
  111. }
  112. else if (num < 0)
  113. {
  114. num = args.Count + num;
  115. if (num < 1)
  116. throw ScriptRuntimeException.IndexOutOfRange("select", 1);
  117. for (int i = num; i < args.Count; i++)
  118. values.Add(args[i]);
  119. }
  120. else
  121. {
  122. throw ScriptRuntimeException.IndexOutOfRange("select", 1);
  123. }
  124. return DynValue.NewTupleNested(values.ToArray());
  125. }
  126. // tonumber (e [, base])
  127. // ----------------------------------------------------------------------------------------------------------------
  128. // When called with no base, tonumber tries to convert its argument to a number. If the argument is already
  129. // a number or a string convertible to a number (see §3.4.2), then tonumber returns this number; otherwise,
  130. // it returns nil.
  131. //
  132. // When called with base, then e should be a string to be interpreted as an integer numeral in that base.
  133. // The base may be any integer between 2 and 36, inclusive. In bases above 10, the letter 'A' (in either
  134. // upper or lower case) represents 10, 'B' represents 11, and so forth, with 'Z' representing 35. If the
  135. // string e is not a valid numeral in the given base, the function returns nil.
  136. [MoonSharpMethod]
  137. public static DynValue tonumber(ScriptExecutionContext executionContext, CallbackArguments args)
  138. {
  139. if (args.Count < 1) throw ScriptRuntimeException.BadArgumentValueExpected(0, "tonumber");
  140. DynValue e = args[0];
  141. DynValue b = args.AsType(1, "tonumber", DataType.Number, true);
  142. if (b.IsNil())
  143. {
  144. if (e.Type == DataType.Number)
  145. return e;
  146. if (e.Type != DataType.String)
  147. return DynValue.Nil;
  148. double d;
  149. if (double.TryParse(e.String, NumberStyles.Any, CultureInfo.InvariantCulture, out d))
  150. {
  151. return DynValue.NewNumber(d);
  152. }
  153. return DynValue.Nil;
  154. }
  155. else
  156. {
  157. //!COMPAT: tonumber supports only 2,8,10 or 16 as base
  158. DynValue ee;
  159. if (args[0].Type != DataType.Number)
  160. ee = args.AsType(0, "tonumber", DataType.String, false);
  161. else
  162. ee = DynValue.NewString(args[0].Number.ToString(CultureInfo.InvariantCulture)); ;
  163. int bb = (int)b.Number;
  164. if (bb != 2 && bb != 8 && bb != 10 && bb != 16)
  165. {
  166. throw new ScriptRuntimeException("bad argument #2 to 'tonumber' (base out of range)");
  167. }
  168. uint uiv = Convert.ToUInt32(ee.String.Trim(), bb);
  169. return DynValue.NewNumber(uiv);
  170. }
  171. }
  172. [MoonSharpMethod]
  173. public static DynValue print(ScriptExecutionContext executionContext, CallbackArguments args)
  174. {
  175. StringBuilder sb = new StringBuilder();
  176. for (int i = 0; i < args.Count; i++)
  177. {
  178. if (i != 0)
  179. sb.Append('\t');
  180. sb.Append(args.AsStringUsingMeta(executionContext, i, "print"));
  181. }
  182. executionContext.GetScript().DebugPrint(sb.ToString());
  183. return DynValue.Nil;
  184. }
  185. }
  186. }