consoleFunctions.cpp 101 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910
  1. //-----------------------------------------------------------------------------
  2. // Copyright (c) 2012 GarageGames, LLC
  3. //
  4. // Permission is hereby granted, free of charge, to any person obtaining a copy
  5. // of this software and associated documentation files (the "Software"), to
  6. // deal in the Software without restriction, including without limitation the
  7. // rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
  8. // sell copies of the Software, and to permit persons to whom the Software is
  9. // furnished to do so, subject to the following conditions:
  10. //
  11. // The above copyright notice and this permission notice shall be included in
  12. // all copies or substantial portions of the Software.
  13. //
  14. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  15. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  16. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  17. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  18. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
  19. // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
  20. // IN THE SOFTWARE.
  21. //-----------------------------------------------------------------------------
  22. #include "platform/platform.h"
  23. #include "console/console.h"
  24. #include "console/consoleInternal.h"
  25. #include "console/engineAPI.h"
  26. #include "console/ast.h"
  27. #ifndef _CONSOLFUNCTIONS_H_
  28. #include "console/consoleFunctions.h"
  29. #endif
  30. #include "core/strings/findMatch.h"
  31. #include "core/strings/stringUnit.h"
  32. #include "core/strings/unicode.h"
  33. #include "core/stream/fileStream.h"
  34. #include "console/compiler.h"
  35. #include "platform/platformInput.h"
  36. #include "core/util/journal/journal.h"
  37. #include "core/util/uuid.h"
  38. #ifdef TORQUE_DEMO_PURCHASE
  39. #include "gui/core/guiCanvas.h"
  40. #endif
  41. // This is a temporary hack to get tools using the library to
  42. // link in this module which contains no other references.
  43. bool LinkConsoleFunctions = false;
  44. // Buffer for expanding script filenames.
  45. static char scriptFilenameBuffer[1024];
  46. bool isInt(const char* str)
  47. {
  48. int len = dStrlen(str);
  49. if(len <= 0)
  50. return false;
  51. // Ingore whitespace
  52. int start = 0;
  53. for(int i = start; i < len; i++)
  54. if(str[i] != ' ')
  55. {
  56. start = i;
  57. break;
  58. }
  59. for(int i = start; i < len; i++)
  60. switch(str[i])
  61. {
  62. case '+': case '-':
  63. if(i != 0)
  64. return false;
  65. break;
  66. case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': case '0':
  67. break;
  68. case ' ': // ignore whitespace
  69. for(int j = i+1; j < len; j++)
  70. if(str[j] != ' ')
  71. return false;
  72. return true;
  73. break;
  74. default:
  75. return false;
  76. }
  77. return true;
  78. }
  79. bool isFloat(const char* str, bool sciOk = false)
  80. {
  81. int len = dStrlen(str);
  82. if(len <= 0)
  83. return false;
  84. // Ingore whitespace
  85. int start = 0;
  86. for(int i = start; i < len; i++)
  87. if(str[i] != ' ')
  88. {
  89. start = i;
  90. break;
  91. }
  92. bool seenDot = false;
  93. int eLoc = -1;
  94. for(int i = 0; i < len; i++)
  95. switch(str[i])
  96. {
  97. case '+': case '-':
  98. if(sciOk)
  99. {
  100. //Haven't found e or scientific notation symbol
  101. if(eLoc == -1)
  102. {
  103. //only allowed in beginning
  104. if(i != 0)
  105. return false;
  106. }
  107. else
  108. {
  109. //if not right after the e
  110. if(i != (eLoc + 1))
  111. return false;
  112. }
  113. }
  114. else
  115. {
  116. //only allowed in beginning
  117. if(i != 0)
  118. return false;
  119. }
  120. break;
  121. case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': case '0':
  122. break;
  123. case 'e': case 'E':
  124. if(!sciOk)
  125. return false;
  126. else
  127. {
  128. //already saw it so can't have 2
  129. if(eLoc != -1)
  130. return false;
  131. eLoc = i;
  132. }
  133. break;
  134. case '.':
  135. if(seenDot | (sciOk && eLoc != -1))
  136. return false;
  137. seenDot = true;
  138. break;
  139. case ' ': // ignore whitespace
  140. for(int j = i+1; j < len; j++)
  141. if(str[j] != ' ')
  142. return false;
  143. return true;
  144. break;
  145. default:
  146. return false;
  147. }
  148. return true;
  149. }
  150. bool isValidIP(const char* ip)
  151. {
  152. unsigned b1, b2, b3, b4;
  153. unsigned char c;
  154. int rc = dSscanf(ip, "%3u.%3u.%3u.%3u%c", &b1, &b2, &b3, &b4, &c);
  155. if (rc != 4 && rc != 5) return false;
  156. if ((b1 | b2 | b3 | b4) > 255) return false;
  157. if (dStrspn(ip, "0123456789.") < dStrlen(ip)) return false;
  158. return true;
  159. }
  160. bool isValidPort(U16 port)
  161. {
  162. return (port >= 0 && port <=65535);
  163. }
  164. //=============================================================================
  165. // String Functions.
  166. //=============================================================================
  167. // MARK: ---- String Functions ----
  168. //-----------------------------------------------------------------------------
  169. DefineConsoleFunction( strasc, int, ( const char* chr ),,
  170. "Return the integer character code value corresponding to the first character in the given string.\n"
  171. "@param chr a (one-character) string.\n"
  172. "@return the UTF32 code value for the first character in the given string.\n"
  173. "@ingroup Strings" )
  174. {
  175. return oneUTF8toUTF32( chr );
  176. }
  177. //-----------------------------------------------------------------------------
  178. DefineConsoleFunction( strformat, const char*, ( const char* format, const char* value ),,
  179. "Format the given value as a string using printf-style formatting.\n"
  180. "@param format A printf-style format string.\n"
  181. "@param value The value argument matching the given format string.\n\n"
  182. "@tsexample\n"
  183. "// Convert the given integer value to a string in a hex notation.\n"
  184. "%hex = strformat( \"%x\", %value );\n"
  185. "@endtsexample\n"
  186. "@ingroup Strings\n"
  187. "@see http://en.wikipedia.org/wiki/Printf" )
  188. {
  189. static const U32 bufSize = 64;
  190. char* pBuffer = Con::getReturnBuffer(bufSize);
  191. const char *pch = format;
  192. pBuffer[0] = '\0';
  193. while (*pch != '\0' && *pch !='%')
  194. pch++;
  195. while (*pch != '\0' && !dIsalpha(*pch))
  196. pch++;
  197. if (*pch == '\0')
  198. {
  199. Con::errorf("strFormat: Invalid format string!\n");
  200. return pBuffer;
  201. }
  202. switch(*pch)
  203. {
  204. case 'c':
  205. case 'C':
  206. case 'd':
  207. case 'i':
  208. case 'o':
  209. case 'u':
  210. case 'x':
  211. case 'X':
  212. dSprintf( pBuffer, bufSize, format, dAtoi( value ) );
  213. break;
  214. case 'e':
  215. case 'E':
  216. case 'f':
  217. case 'g':
  218. case 'G':
  219. dSprintf( pBuffer, bufSize, format, dAtof( value ) );
  220. break;
  221. default:
  222. Con::errorf("strFormat: Invalid format string!\n");
  223. break;
  224. }
  225. return pBuffer;
  226. }
  227. //-----------------------------------------------------------------------------
  228. DefineConsoleFunction( strcmp, S32, ( const char* str1, const char* str2 ),,
  229. "Compares two strings using case-<b>sensitive</b> comparison.\n"
  230. "@param str1 The first string.\n"
  231. "@param str2 The second string.\n"
  232. "@return 0 if both strings are equal, a value <0 if the first character different in str1 has a smaller character code "
  233. "value than the character at the same position in str2, and a value >1 otherwise.\n\n"
  234. "@tsexample\n"
  235. "if( strcmp( %var, \"foobar\" ) == 0 )\n"
  236. " echo( \"%var is equal to 'foobar'\" );\n"
  237. "@endtsexample\n"
  238. "@see stricmp\n"
  239. "@see strnatcmp\n"
  240. "@ingroup Strings" )
  241. {
  242. return dStrcmp( str1, str2 );
  243. }
  244. //-----------------------------------------------------------------------------
  245. DefineConsoleFunction( stricmp, S32, ( const char* str1, const char* str2 ),,
  246. "Compares two strings using case-<b>insensitive</b> comparison.\n"
  247. "@param str1 The first string.\n"
  248. "@param str2 The second string.\n"
  249. "@return 0 if both strings are equal, a value <0 if the first character different in str1 has a smaller character code "
  250. "value than the character at the same position in str2, and a value >0 otherwise.\n\n"
  251. "@tsexample\n"
  252. "if( stricmp( \"FOObar\", \"foobar\" ) == 0 )\n"
  253. " echo( \"this is always true\" );\n"
  254. "@endtsexample\n"
  255. "@see strcmp\n"
  256. "@see strinatcmp\n"
  257. "@ingroup Strings" )
  258. {
  259. return dStricmp( str1, str2 );
  260. }
  261. //-----------------------------------------------------------------------------
  262. DefineConsoleFunction( strnatcmp, S32, ( const char* str1, const char* str2 ),,
  263. "Compares two strings using \"natural order\" case-<b>sensitive</b> comparison.\n"
  264. "Natural order means that rather than solely comparing single character code values, strings are ordered in a "
  265. "natural way. For example, the string \"hello10\" is considered greater than the string \"hello2\" even though "
  266. "the first numeric character in \"hello10\" actually has a smaller character value than the corresponding character "
  267. "in \"hello2\". However, since 10 is greater than 2, strnatcmp will put \"hello10\" after \"hello2\".\n"
  268. "@param str1 The first string.\n"
  269. "@param str2 The second string.\n\n"
  270. "@return 0 if the strings are equal, a value >0 if @a str1 comes after @a str2 in a natural order, and a value "
  271. "<0 if @a str1 comes before @a str2 in a natural order.\n\n"
  272. "@tsexample\n"
  273. "// Bubble sort 10 elements of %array using natural order\n"
  274. "do\n"
  275. "{\n"
  276. " %swapped = false;\n"
  277. " for( %i = 0; %i < 10 - 1; %i ++ )\n"
  278. " if( strnatcmp( %array[ %i ], %array[ %i + 1 ] ) > 0 )\n"
  279. " {\n"
  280. " %temp = %array[ %i ];\n"
  281. " %array[ %i ] = %array[ %i + 1 ];\n"
  282. " %array[ %i + 1 ] = %temp;\n"
  283. " %swapped = true;\n"
  284. " }\n"
  285. "}\n"
  286. "while( %swapped );\n"
  287. "@endtsexample\n"
  288. "@see strcmp\n"
  289. "@see strinatcmp\n"
  290. "@ingroup Strings" )
  291. {
  292. return dStrnatcmp( str1, str2 );
  293. }
  294. //-----------------------------------------------------------------------------
  295. DefineConsoleFunction( strinatcmp, S32, ( const char* str1, const char* str2 ),,
  296. "Compares two strings using \"natural order\" case-<b>insensitive</b> comparison.\n"
  297. "Natural order means that rather than solely comparing single character code values, strings are ordered in a "
  298. "natural way. For example, the string \"hello10\" is considered greater than the string \"hello2\" even though "
  299. "the first numeric character in \"hello10\" actually has a smaller character value than the corresponding character "
  300. "in \"hello2\". However, since 10 is greater than 2, strnatcmp will put \"hello10\" after \"hello2\".\n"
  301. "@param str1 The first string.\n"
  302. "@param str2 The second string.\n"
  303. "@return 0 if the strings are equal, a value >0 if @a str1 comes after @a str2 in a natural order, and a value "
  304. "<0 if @a str1 comes before @a str2 in a natural order.\n\n"
  305. "@tsexample\n\n"
  306. "// Bubble sort 10 elements of %array using natural order\n"
  307. "do\n"
  308. "{\n"
  309. " %swapped = false;\n"
  310. " for( %i = 0; %i < 10 - 1; %i ++ )\n"
  311. " if( strnatcmp( %array[ %i ], %array[ %i + 1 ] ) > 0 )\n"
  312. " {\n"
  313. " %temp = %array[ %i ];\n"
  314. " %array[ %i ] = %array[ %i + 1 ];\n"
  315. " %array[ %i + 1 ] = %temp;\n"
  316. " %swapped = true;\n"
  317. " }\n"
  318. "}\n"
  319. "while( %swapped );\n"
  320. "@endtsexample\n"
  321. "@see stricmp\n"
  322. "@see strnatcmp\n"
  323. "@ingroup Strings" )
  324. {
  325. return dStrnatcasecmp( str1, str2 );
  326. }
  327. //-----------------------------------------------------------------------------
  328. DefineConsoleFunction( strlen, S32, ( const char* str ),,
  329. "Get the length of the given string in bytes.\n"
  330. "@note This does <b>not</b> return a true character count for strings with multi-byte characters!\n"
  331. "@param str A string.\n"
  332. "@return The length of the given string in bytes.\n"
  333. "@ingroup Strings" )
  334. {
  335. return dStrlen( str );
  336. }
  337. //-----------------------------------------------------------------------------
  338. DefineConsoleFunction( strlenskip, S32, ( const char* str, const char* first, const char* last ),,
  339. "Calculate the length of a string in characters, skipping everything between and including first and last.\n"
  340. "@param str A string.\n"
  341. "@param first First character to look for to skip block of text.\n"
  342. "@param last Second character to look for to skip block of text.\n"
  343. "@return The length of the given string skipping blocks of text between characters.\n"
  344. "@ingroup Strings" )
  345. {
  346. const UTF8* pos = str;
  347. U32 size = 0;
  348. U32 length = dStrlen(str);
  349. bool count = true;
  350. //loop through each character counting each character, skipping tags (anything with < followed by >)
  351. for(U32 i = 0; i < length; i++, pos++)
  352. {
  353. if(count)
  354. {
  355. if(*pos == first[0])
  356. count = false;
  357. else
  358. size++;
  359. }
  360. else
  361. {
  362. if(*pos == last[0])
  363. count = true;
  364. }
  365. }
  366. return S32(size);
  367. }
  368. //-----------------------------------------------------------------------------
  369. DefineConsoleFunction( strstr, S32, ( const char* string, const char* substring ),,
  370. "Find the start of @a substring in the given @a string searching from left to right.\n"
  371. "@param string The string to search.\n"
  372. "@param substring The string to search for.\n"
  373. "@return The index into @a string at which the first occurrence of @a substring was found or -1 if @a substring could not be found.\n\n"
  374. "@tsexample\n"
  375. "strstr( \"abcd\", \"c\" ) // Returns 2.\n"
  376. "@endtsexample\n"
  377. "@ingroup Strings" )
  378. {
  379. const char* retpos = dStrstr( string, substring );
  380. if( !retpos )
  381. return -1;
  382. return retpos - string;
  383. }
  384. //-----------------------------------------------------------------------------
  385. DefineConsoleFunction( strpos, S32, ( const char* haystack, const char* needle, S32 offset ), ( 0 ),
  386. "Find the start of @a needle in @a haystack searching from left to right beginning at the given offset.\n"
  387. "@param haystack The string to search.\n"
  388. "@param needle The string to search for.\n"
  389. "@return The index at which the first occurrence of @a needle was found in @a haystack or -1 if no match was found.\n\n"
  390. "@tsexample\n"
  391. "strpos( \"b ab\", \"b\", 1 ) // Returns 3.\n"
  392. "@endtsexample\n"
  393. "@ingroup Strings" )
  394. {
  395. S32 start = offset;
  396. U32 sublen = dStrlen( needle );
  397. U32 strlen = dStrlen( haystack );
  398. if(start < 0)
  399. return -1;
  400. if(sublen + start > strlen)
  401. return -1;
  402. for(; start + sublen <= strlen; start++)
  403. if(!dStrncmp(haystack + start, needle, sublen))
  404. return start;
  405. return -1;
  406. }
  407. //-----------------------------------------------------------------------------
  408. DefineConsoleFunction( strposr, S32, ( const char* haystack, const char* needle, S32 offset ), ( 0 ),
  409. "Find the start of @a needle in @a haystack searching from right to left beginning at the given offset.\n"
  410. "@param haystack The string to search.\n"
  411. "@param needle The string to search for.\n"
  412. "@return The index at which the first occurrence of @a needle was found in @a heystack or -1 if no match was found.\n\n"
  413. "@tsexample\n"
  414. "strposr( \"b ab\", \"b\", 1 ) // Returns 2.\n"
  415. "@endtsexample\n"
  416. "@ingroup Strings" )
  417. {
  418. U32 sublen = dStrlen( needle );
  419. U32 strlen = dStrlen( haystack );
  420. S32 start = strlen - offset;
  421. if(start < 0 || start > strlen)
  422. return -1;
  423. if (start + sublen > strlen)
  424. start = strlen - sublen;
  425. for(; start >= 0; start--)
  426. if(!dStrncmp(haystack + start, needle, sublen))
  427. return start;
  428. return -1;
  429. }
  430. //-----------------------------------------------------------------------------
  431. DefineConsoleFunction( ltrim, const char*, ( const char* str ),,
  432. "Remove leading whitespace from the string.\n"
  433. "@param str A string.\n"
  434. "@return A string that is the same as @a str but with any leading (i.e. leftmost) whitespace removed.\n\n"
  435. "@tsexample\n"
  436. "ltrim( \" string \" ); // Returns \"string \".\n"
  437. "@endtsexample\n"
  438. "@see rtrim\n"
  439. "@see trim\n"
  440. "@ingroup Strings" )
  441. {
  442. const char *ret = str;
  443. while(*ret == ' ' || *ret == '\n' || *ret == '\t')
  444. ret++;
  445. return ret;
  446. }
  447. //-----------------------------------------------------------------------------
  448. DefineConsoleFunction( rtrim, const char*, ( const char* str ),,
  449. "Remove trailing whitespace from the string.\n"
  450. "@param str A string.\n"
  451. "@return A string that is the same as @a str but with any trailing (i.e. rightmost) whitespace removed.\n\n"
  452. "@tsexample\n"
  453. "rtrim( \" string \" ); // Returns \" string\".\n"
  454. "@endtsexample\n"
  455. "@see ltrim\n"
  456. "@see trim\n"
  457. "@ingroup Strings" )
  458. {
  459. S32 firstWhitespace = 0;
  460. S32 pos = 0;
  461. while(str[pos])
  462. {
  463. if(str[pos] != ' ' && str[pos] != '\n' && str[pos] != '\t')
  464. firstWhitespace = pos + 1;
  465. pos++;
  466. }
  467. char *ret = Con::getReturnBuffer(firstWhitespace + 1);
  468. dStrncpy(ret, str, firstWhitespace);
  469. ret[firstWhitespace] = 0;
  470. return ret;
  471. }
  472. //-----------------------------------------------------------------------------
  473. DefineConsoleFunction( trim, const char*, ( const char* str ),,
  474. "Remove leading and trailing whitespace from the string.\n"
  475. "@param str A string.\n"
  476. "@return A string that is the same as @a str but with any leading (i.e. leftmost) and trailing (i.e. rightmost) whitespace removed.\n\n"
  477. "@tsexample\n"
  478. "trim( \" string \" ); // Returns \"string\".\n"
  479. "@endtsexample\n"
  480. "@ingroup Strings" )
  481. {
  482. const char *ptr = str;
  483. while(*ptr == ' ' || *ptr == '\n' || *ptr == '\t')
  484. ptr++;
  485. S32 firstWhitespace = 0;
  486. S32 pos = 0;
  487. while(ptr[pos])
  488. {
  489. if(ptr[pos] != ' ' && ptr[pos] != '\n' && ptr[pos] != '\t')
  490. firstWhitespace = pos + 1;
  491. pos++;
  492. }
  493. char *ret = Con::getReturnBuffer(firstWhitespace + 1);
  494. dStrncpy(ret, ptr, firstWhitespace);
  495. ret[firstWhitespace] = 0;
  496. return ret;
  497. }
  498. //-----------------------------------------------------------------------------
  499. DefineConsoleFunction( stripChars, const char*, ( const char* str, const char* chars ),,
  500. "Remove all occurrences of characters contained in @a chars from @a str.\n"
  501. "@param str The string to filter characters out from.\n"
  502. "@param chars A string of characters to filter out from @a str.\n"
  503. "@return A version of @a str with all occurrences of characters contained in @a chars filtered out.\n\n"
  504. "@tsexample\n"
  505. "stripChars( \"teststring\", \"se\" ); // Returns \"tttring\"."
  506. "@endtsexample\n"
  507. "@ingroup Strings" )
  508. {
  509. char* ret = Con::getReturnBuffer( dStrlen( str ) + 1 );
  510. dStrcpy( ret, str );
  511. U32 pos = dStrcspn( ret, chars );
  512. while ( pos < dStrlen( ret ) )
  513. {
  514. dStrcpy( ret + pos, ret + pos + 1 );
  515. pos = dStrcspn( ret, chars );
  516. }
  517. return( ret );
  518. }
  519. //-----------------------------------------------------------------------------
  520. DefineConsoleFunction( strlwr, const char*, ( const char* str ),,
  521. "Return an all lower-case version of the given string.\n"
  522. "@param str A string.\n"
  523. "@return A version of @a str with all characters converted to lower-case.\n\n"
  524. "@tsexample\n"
  525. "strlwr( \"TesT1\" ) // Returns \"test1\"\n"
  526. "@endtsexample\n"
  527. "@see strupr\n"
  528. "@ingroup Strings" )
  529. {
  530. char *ret = Con::getReturnBuffer(dStrlen(str) + 1);
  531. dStrcpy(ret, str);
  532. return dStrlwr(ret);
  533. }
  534. //-----------------------------------------------------------------------------
  535. DefineConsoleFunction( strupr, const char*, ( const char* str ),,
  536. "Return an all upper-case version of the given string.\n"
  537. "@param str A string.\n"
  538. "@return A version of @a str with all characters converted to upper-case.\n\n"
  539. "@tsexample\n"
  540. "strupr( \"TesT1\" ) // Returns \"TEST1\"\n"
  541. "@endtsexample\n"
  542. "@see strlwr\n"
  543. "@ingroup Strings" )
  544. {
  545. char *ret = Con::getReturnBuffer(dStrlen(str) + 1);
  546. dStrcpy(ret, str);
  547. return dStrupr(ret);
  548. }
  549. //-----------------------------------------------------------------------------
  550. DefineConsoleFunction( strchr, const char*, ( const char* str, const char* chr ),,
  551. "Find the first occurrence of the given character in @a str.\n"
  552. "@param str The string to search.\n"
  553. "@param chr The character to search for. Only the first character from the string is taken.\n"
  554. "@return The remainder of the input string starting with the given character or the empty string if the character could not be found.\n\n"
  555. "@see strrchr\n"
  556. "@ingroup Strings" )
  557. {
  558. const char *ret = dStrchr( str, chr[ 0 ] );
  559. return ret ? ret : "";
  560. }
  561. //-----------------------------------------------------------------------------
  562. DefineConsoleFunction( strrchr, const char*, ( const char* str, const char* chr ),,
  563. "Find the last occurrence of the given character in @a str."
  564. "@param str The string to search.\n"
  565. "@param chr The character to search for. Only the first character from the string is taken.\n"
  566. "@return The remainder of the input string starting with the given character or the empty string if the character could not be found.\n\n"
  567. "@see strchr\n"
  568. "@ingroup Strings" )
  569. {
  570. const char *ret = dStrrchr( str, chr[ 0 ] );
  571. return ret ? ret : "";
  572. }
  573. //-----------------------------------------------------------------------------
  574. DefineConsoleFunction( strreplace, const char*, ( const char* source, const char* from, const char* to ),,
  575. "Replace all occurrences of @a from in @a source with @a to.\n"
  576. "@param source The string in which to replace the occurrences of @a from.\n"
  577. "@param from The string to replace in @a source.\n"
  578. "@param to The string with which to replace occurrences of @from.\n"
  579. "@return A string with all occurrences of @a from in @a source replaced by @a to.\n\n"
  580. "@tsexample\n"
  581. "strreplace( \"aabbccbb\", \"bb\", \"ee\" ) // Returns \"aaeeccee\".\n"
  582. "@endtsexample\n"
  583. "@ingroup Strings" )
  584. {
  585. S32 fromLen = dStrlen( from );
  586. if(!fromLen)
  587. return source;
  588. S32 toLen = dStrlen( to );
  589. S32 count = 0;
  590. const char *scan = source;
  591. while(scan)
  592. {
  593. scan = dStrstr(scan, from);
  594. if(scan)
  595. {
  596. scan += fromLen;
  597. count++;
  598. }
  599. }
  600. char *ret = Con::getReturnBuffer(dStrlen(source) + 1 + (toLen - fromLen) * count);
  601. U32 scanp = 0;
  602. U32 dstp = 0;
  603. for(;;)
  604. {
  605. const char *scan = dStrstr(source + scanp, from);
  606. if(!scan)
  607. {
  608. dStrcpy(ret + dstp, source + scanp);
  609. break;
  610. }
  611. U32 len = scan - (source + scanp);
  612. dStrncpy(ret + dstp, source + scanp, len);
  613. dstp += len;
  614. dStrcpy(ret + dstp, to);
  615. dstp += toLen;
  616. scanp += len + fromLen;
  617. }
  618. return ret;
  619. }
  620. //-----------------------------------------------------------------------------
  621. DefineConsoleFunction( strrepeat, const char*, ( const char* str, S32 numTimes, const char* delimiter ), ( "" ),
  622. "Return a string that repeats @a str @a numTimes number of times delimiting each occurrence with @a delimiter.\n"
  623. "@param str The string to repeat multiple times.\n"
  624. "@param numTimes The number of times to repeat @a str in the result string.\n"
  625. "@param delimiter The string to put between each repetition of @a str.\n"
  626. "@return A string containing @a str repeated @a numTimes times.\n\n"
  627. "@tsexample\n"
  628. "strrepeat( \"a\", 5, \"b\" ) // Returns \"ababababa\".\n"
  629. "@endtsexample\n"
  630. "@ingroup Strings" )
  631. {
  632. StringBuilder result;
  633. bool isFirst = false;
  634. for( U32 i = 0; i < numTimes; ++ i )
  635. {
  636. if( !isFirst )
  637. result.append( delimiter );
  638. result.append( str );
  639. isFirst = false;
  640. }
  641. return Con::getReturnBuffer( result );
  642. }
  643. //-----------------------------------------------------------------------------
  644. DefineConsoleFunction( getSubStr, const char*, ( const char* str, S32 start, S32 numChars ), ( -1 ),
  645. "@brief Return a substring of @a str starting at @a start and continuing either through to the end of @a str "
  646. "(if @a numChars is -1) or for @a numChars characters (except if this would exceed the actual source "
  647. "string length).\n"
  648. "@param str The string from which to extract a substring.\n"
  649. "@param start The offset at which to start copying out characters.\n"
  650. "@param numChars Optional argument to specify the number of characters to copy. If this is -1, all characters up the end "
  651. "of the input string are copied.\n"
  652. "@return A string that contains the given portion of the input string.\n\n"
  653. "@tsexample\n"
  654. "getSubStr( \"foobar\", 1, 2 ) // Returns \"oo\".\n"
  655. "@endtsexample\n\n"
  656. "@ingroup Strings" )
  657. {
  658. S32 baseLen = dStrlen( str );
  659. if( numChars == -1 )
  660. numChars = baseLen - start;
  661. if (start < 0 || numChars < 0) {
  662. Con::errorf(ConsoleLogEntry::Script, "getSubStr(...): error, starting position and desired length must be >= 0: (%d, %d)", start, numChars);
  663. return "";
  664. }
  665. if (baseLen < start)
  666. return "";
  667. U32 actualLen = numChars;
  668. if (start + numChars > baseLen)
  669. actualLen = baseLen - start;
  670. char *ret = Con::getReturnBuffer(actualLen + 1);
  671. dStrncpy(ret, str + start, actualLen);
  672. ret[actualLen] = '\0';
  673. return ret;
  674. }
  675. //-----------------------------------------------------------------------------
  676. DefineConsoleFunction( strIsMatchExpr, bool, ( const char* pattern, const char* str, bool caseSensitive ), ( false ),
  677. "Match a pattern against a string.\n"
  678. "@param pattern The wildcard pattern to match against. The pattern can include characters, '*' to match "
  679. "any number of characters and '?' to match a single character.\n"
  680. "@param str The string which should be matched against @a pattern.\n"
  681. "@param caseSensitive If true, characters in the pattern are matched in case-sensitive fashion against "
  682. "this string. If false, differences in casing are ignored.\n"
  683. "@return True if @a str matches the given @a pattern.\n\n"
  684. "@tsexample\n"
  685. "strIsMatchExpr( \"f?o*R\", \"foobar\" ) // Returns true.\n"
  686. "@endtsexample\n"
  687. "@see strIsMatchMultipleExpr\n"
  688. "@ingroup Strings" )
  689. {
  690. return FindMatch::isMatch( pattern, str, caseSensitive );
  691. }
  692. //-----------------------------------------------------------------------------
  693. DefineConsoleFunction( strIsMatchMultipleExpr, bool, ( const char* patterns, const char* str, bool caseSensitive ), ( false ),
  694. "Match a multiple patterns against a single string.\n"
  695. "@param patterns A tab-separated list of patterns. Each pattern can include charaters, '*' to match "
  696. "any number of characters and '?' to match a single character. Each of the patterns is tried in turn.\n"
  697. "@param str The string which should be matched against @a patterns.\n"
  698. "@param caseSensitive If true, characters in the pattern are matched in case-sensitive fashion against "
  699. "this string. If false, differences in casing are ignored.\n"
  700. "@return True if @a str matches any of the given @a patterns.\n\n"
  701. "@tsexample\n"
  702. "strIsMatchMultipleExpr( \"*.cs *.gui *.mis\", \"mymission.mis\" ) // Returns true.\n"
  703. "@endtsexample\n"
  704. "@see strIsMatchExpr\n"
  705. "@ingroup Strings" )
  706. {
  707. return FindMatch::isMatchMultipleExprs( patterns, str, caseSensitive );
  708. }
  709. //-----------------------------------------------------------------------------
  710. DefineConsoleFunction( getTrailingNumber, S32, ( const char* str ),,
  711. "Get the numeric suffix of the given input string.\n"
  712. "@param str The string from which to read out the numeric suffix.\n"
  713. "@return The numeric value of the number suffix of @a str or -1 if @a str has no such suffix.\n\n"
  714. "@tsexample\n"
  715. "getTrailingNumber( \"test123\" ) // Returns '123'.\n"
  716. "@endtsexample\n\n"
  717. "@see stripTrailingNumber\n"
  718. "@ingroup Strings" )
  719. {
  720. S32 suffix = -1;
  721. String outStr( String::GetTrailingNumber( str, suffix ) );
  722. return suffix;
  723. }
  724. //-----------------------------------------------------------------------------
  725. DefineConsoleFunction( stripTrailingNumber, String, ( const char* str ),,
  726. "Strip a numeric suffix from the given string.\n"
  727. "@param str The string from which to strip its numeric suffix.\n"
  728. "@return The string @a str without its number suffix or the original string @a str if it has no such suffix.\n\n"
  729. "@tsexample\n"
  730. "stripTrailingNumber( \"test123\" ) // Returns \"test\".\n"
  731. "@endtsexample\n\n"
  732. "@see getTrailingNumber\n"
  733. "@ingroup Strings" )
  734. {
  735. S32 suffix;
  736. return String::GetTrailingNumber( str, suffix );
  737. }
  738. //-----------------------------------------------------------------------------
  739. DefineConsoleFunction( getFirstNumber, String, ( const char* str ),,
  740. "Get the first occuring number from @a str.\n"
  741. "@param str The string from which to read out the first number.\n"
  742. "@return String representation of the number or "" if no number.\n\n")
  743. {
  744. U32 start;
  745. U32 end;
  746. return String::GetFirstNumber(str, start, end);
  747. }
  748. //----------------------------------------------------------------
  749. DefineConsoleFunction( isspace, bool, ( const char* str, S32 index ),,
  750. "Test whether the character at the given position is a whitespace character.\n"
  751. "Characters such as tab, space, or newline are considered whitespace.\n"
  752. "@param str The string to test.\n"
  753. "@param index The index of a character in @a str.\n"
  754. "@return True if the character at the given index in @a str is a whitespace character; false otherwise.\n\n"
  755. "@see isalnum\n"
  756. "@ingroup Strings" )
  757. {
  758. if( index >= 0 && index < dStrlen( str ) )
  759. return dIsspace( str[ index ] );
  760. else
  761. return false;
  762. }
  763. //----------------------------------------------------------------
  764. DefineConsoleFunction( isalnum, bool, ( const char* str, S32 index ),,
  765. "Test whether the character at the given position is an alpha-numeric character.\n"
  766. "Alpha-numeric characters are characters that are either alphabetic (a-z, A-Z) or numbers (0-9).\n"
  767. "@param str The string to test.\n"
  768. "@param index The index of a character in @a str.\n"
  769. "@return True if the character at the given index in @a str is an alpha-numeric character; false otherwise.\n\n"
  770. "@see isspace\n"
  771. "@ingroup Strings" )
  772. {
  773. if( index >= 0 && index < dStrlen( str ) )
  774. return dIsalnum( str[ index ] );
  775. else
  776. return false;
  777. }
  778. //----------------------------------------------------------------
  779. DefineConsoleFunction( startsWith, bool, ( const char* str, const char* prefix, bool caseSensitive ), ( false ),
  780. "Test whether the given string begins with the given prefix.\n"
  781. "@param str The string to test.\n"
  782. "@param prefix The potential prefix of @a str.\n"
  783. "@param caseSensitive If true, the comparison will be case-sensitive; if false, differences in casing will "
  784. "not be taken into account.\n"
  785. "@return True if the first characters in @a str match the complete contents of @a prefix; false otherwise.\n\n"
  786. "@tsexample\n"
  787. "startsWith( \"TEST123\", \"test\" ) // Returns true.\n"
  788. "@endtsexample\n"
  789. "@see endsWith\n"
  790. "@ingroup Strings" )
  791. {
  792. // if the target string is empty, return true (all strings start with the empty string)
  793. S32 srcLen = dStrlen( str );
  794. S32 targetLen = dStrlen( prefix );
  795. if( targetLen == 0 )
  796. return true;
  797. // else if the src string is empty, return false (empty src does not start with non-empty target)
  798. else if( srcLen == 0 )
  799. return false;
  800. if( caseSensitive )
  801. return ( dStrncmp( str, prefix, targetLen ) == 0 );
  802. // both src and target are non empty, create temp buffers for lowercase operation
  803. char* srcBuf = new char[ srcLen + 1 ];
  804. char* targetBuf = new char[ targetLen + 1 ];
  805. // copy src and target into buffers
  806. dStrcpy( srcBuf, str );
  807. dStrcpy( targetBuf, prefix );
  808. // reassign src/target pointers to lowercase versions
  809. str = dStrlwr( srcBuf );
  810. prefix = dStrlwr( targetBuf );
  811. // do the comparison
  812. bool startsWith = dStrncmp( str, prefix, targetLen ) == 0;
  813. // delete temp buffers
  814. delete [] srcBuf;
  815. delete [] targetBuf;
  816. return startsWith;
  817. }
  818. //----------------------------------------------------------------
  819. DefineConsoleFunction( endsWith, bool, ( const char* str, const char* suffix, bool caseSensitive ), ( false ),
  820. "@brief Test whether the given string ends with the given suffix.\n\n"
  821. "@param str The string to test.\n"
  822. "@param suffix The potential suffix of @a str.\n"
  823. "@param caseSensitive If true, the comparison will be case-sensitive; if false, differences in casing will "
  824. "not be taken into account.\n"
  825. "@return True if the last characters in @a str match the complete contents of @a suffix; false otherwise.\n\n"
  826. "@tsexample\n"
  827. "startsWith( \"TEST123\", \"123\" ) // Returns true.\n"
  828. "@endtsexample\n\n"
  829. "@see startsWith\n"
  830. "@ingroup Strings" )
  831. {
  832. // if the target string is empty, return true (all strings end with the empty string)
  833. S32 srcLen = dStrlen( str );
  834. S32 targetLen = dStrlen( suffix );
  835. if (targetLen == 0)
  836. return true;
  837. // else if the src string is empty, return false (empty src does not end with non-empty target)
  838. else if (srcLen == 0)
  839. return false;
  840. else if( targetLen > srcLen )
  841. return false;
  842. if( caseSensitive )
  843. return ( dStrcmp( &str[ srcLen - targetLen ], suffix ) == 0 );
  844. // both src and target are non empty, create temp buffers for lowercase operation
  845. char* srcBuf = new char[ srcLen + 1 ];
  846. char* targetBuf = new char[ targetLen + 1 ];
  847. // copy src and target into buffers
  848. dStrcpy( srcBuf, str );
  849. dStrcpy( targetBuf, suffix );
  850. // reassign src/target pointers to lowercase versions
  851. str = dStrlwr( srcBuf );
  852. suffix = dStrlwr( targetBuf );
  853. // set the src pointer to the appropriate place to check the end of the string
  854. str += srcLen - targetLen;
  855. // do the comparison
  856. bool endsWith = dStrcmp( str, suffix ) == 0;
  857. // delete temp buffers
  858. delete [] srcBuf;
  859. delete [] targetBuf;
  860. return endsWith;
  861. }
  862. //----------------------------------------------------------------
  863. DefineConsoleFunction( strchrpos, S32, ( const char* str, const char* chr, S32 start ), ( 0 ),
  864. "Find the first occurrence of the given character in the given string.\n"
  865. "@param str The string to search.\n"
  866. "@param chr The character to look for. Only the first character of this string will be searched for.\n"
  867. "@param start The index into @a str at which to start searching for the given character.\n"
  868. "@return The index of the first occurrence of @a chr in @a str or -1 if @a str does not contain the given character.\n\n"
  869. "@tsexample\n"
  870. "strchrpos( \"test\", \"s\" ) // Returns 2.\n"
  871. "@endtsexample\n"
  872. "@ingroup Strings" )
  873. {
  874. if( start != 0 && start >= dStrlen( str ) )
  875. return -1;
  876. const char* ret = dStrchr( &str[ start ], chr[ 0 ] );
  877. return ret ? ret - str : -1;
  878. }
  879. //----------------------------------------------------------------
  880. DefineConsoleFunction( strrchrpos, S32, ( const char* str, const char* chr, S32 start ), ( 0 ),
  881. "Find the last occurrence of the given character in the given string.\n"
  882. "@param str The string to search.\n"
  883. "@param chr The character to look for. Only the first character of this string will be searched for.\n"
  884. "@param start The index into @a str at which to start searching for the given character.\n"
  885. "@return The index of the last occurrence of @a chr in @a str or -1 if @a str does not contain the given character.\n\n"
  886. "@tsexample\n"
  887. "strrchrpos( \"test\", \"t\" ) // Returns 3.\n"
  888. "@endtsexample\n"
  889. "@ingroup Strings" )
  890. {
  891. if( start != 0 && start >= dStrlen( str ) )
  892. return -1;
  893. const char* ret = dStrrchr( str, chr[ 0 ] );
  894. if( !ret )
  895. return -1;
  896. S32 index = ret - str;
  897. if( index < start )
  898. return -1;
  899. return index;
  900. }
  901. //----------------------------------------------------------------
  902. DefineConsoleFunction( strToggleCaseToWords, const char*, ( const char* str ),,
  903. "Parse a Toggle Case word into separate words.\n"
  904. "@param str The string to parse.\n"
  905. "@return new string space separated.\n\n"
  906. "@tsexample\n"
  907. "strToggleCaseToWords( \"HelloWorld\" ) // Returns \"Hello World\".\n"
  908. "@endtsexample\n"
  909. "@ingroup Strings" )
  910. {
  911. String newStr;
  912. for(S32 i = 0; str[i]; i++)
  913. {
  914. //If capitol add a space
  915. if(i != 0 && str[i] >= 65 && str[i] <= 90)
  916. newStr += " ";
  917. newStr += str[i];
  918. }
  919. return Con::getReturnBuffer(newStr);
  920. }
  921. //----------------------------------------------------------------
  922. // Warning: isInt and isFloat are very 'strict' and might need to be adjusted to allow other values. //seanmc
  923. DefineConsoleFunction( isInt, bool, ( const char* str),,
  924. "Returns true if the string is an integer.\n"
  925. "@param str The string to test.\n"
  926. "@return true if @a str is an integer and false if not\n\n"
  927. "@tsexample\n"
  928. "isInt( \"13\" ) // Returns true.\n"
  929. "@endtsexample\n"
  930. "@ingroup Strings" )
  931. {
  932. return isInt(str);
  933. }
  934. //----------------------------------------------------------------
  935. DefineConsoleFunction( isFloat, bool, ( const char* str, bool sciOk), (false),
  936. "Returns true if the string is a float.\n"
  937. "@param str The string to test.\n"
  938. "@param sciOk Test for correct scientific notation and accept it (ex. 1.2e+14)"
  939. "@return true if @a str is a float and false if not\n\n"
  940. "@tsexample\n"
  941. "isFloat( \"13.5\" ) // Returns true.\n"
  942. "@endtsexample\n"
  943. "@ingroup Strings" )
  944. {
  945. return isFloat(str, sciOk);
  946. }
  947. //----------------------------------------------------------------
  948. DefineConsoleFunction( isValidPort, bool, ( const char* str),,
  949. "Returns true if the string is a valid port number.\n"
  950. "@param str The string to test.\n"
  951. "@return true if @a str is a port and false if not\n\n"
  952. "@tsexample\n"
  953. "isValidPort( \"8080\" ) // Returns true.\n"
  954. "@endtsexample\n"
  955. "@ingroup Strings" )
  956. {
  957. if(isInt(str))
  958. {
  959. U16 port = dAtous(str);
  960. return isValidPort(port);
  961. }
  962. else
  963. return false;
  964. }
  965. //----------------------------------------------------------------
  966. DefineConsoleFunction( isValidIP, bool, ( const char* str),,
  967. "Returns true if the string is a valid ip address, excepts localhost.\n"
  968. "@param str The string to test.\n"
  969. "@return true if @a str is a valid ip address and false if not\n\n"
  970. "@tsexample\n"
  971. "isValidIP( \"localhost\" ) // Returns true.\n"
  972. "@endtsexample\n"
  973. "@ingroup Strings" )
  974. {
  975. if(dStrcmp(str, "localhost") == 0)
  976. {
  977. return true;
  978. }
  979. else
  980. return isValidIP(str);
  981. }
  982. //----------------------------------------------------------------
  983. // Torque won't normally add another string if it already exists with another casing,
  984. // so this forces the addition. It should be called once near the start, such as in main.cs.
  985. ConsoleFunction(addCaseSensitiveStrings,void,2,0,"[string1, string2, ...]"
  986. "Adds case sensitive strings to the StringTable.")
  987. {
  988. for(int i = 1; i < argc; i++)
  989. StringTable->insert(argv[i], true);
  990. }
  991. //=============================================================================
  992. // Field Manipulators.
  993. //=============================================================================
  994. // MARK: ---- Field Manipulators ----
  995. //-----------------------------------------------------------------------------
  996. DefineConsoleFunction( getWord, const char*, ( const char* text, S32 index ),,
  997. "Extract the word at the given @a index in the whitespace-separated list in @a text.\n"
  998. "Words in @a text must be separated by newlines, spaces, and/or tabs.\n"
  999. "@param text A whitespace-separated list of words.\n"
  1000. "@param index The zero-based index of the word to extract.\n"
  1001. "@return The word at the given index or \"\" if the index is out of range.\n\n"
  1002. "@tsexample\n"
  1003. "getWord( \"a b c\", 1 ) // Returns \"b\"\n"
  1004. "@endtsexample\n\n"
  1005. "@see getWords\n"
  1006. "@see getWordCount\n"
  1007. "@see getField\n"
  1008. "@see getRecord\n"
  1009. "@ingroup FieldManip" )
  1010. {
  1011. return Con::getReturnBuffer( StringUnit::getUnit( text, index, " \t\n") );
  1012. }
  1013. //-----------------------------------------------------------------------------
  1014. DefineConsoleFunction( getWords, const char*, ( const char* text, S32 startIndex, S32 endIndex ), ( -1 ),
  1015. "Extract a range of words from the given @a startIndex onwards thru @a endIndex.\n"
  1016. "Words in @a text must be separated by newlines, spaces, and/or tabs.\n"
  1017. "@param text A whitespace-separated list of words.\n"
  1018. "@param startIndex The zero-based index of the first word to extract from @a text.\n"
  1019. "@param endIndex The zero-based index of the last word to extract from @a text. If this is -1, all words beginning "
  1020. "with @a startIndex are extracted from @a text.\n"
  1021. "@return A string containing the specified range of words from @a text or \"\" if @a startIndex "
  1022. "is out of range or greater than @a endIndex.\n\n"
  1023. "@tsexample\n"
  1024. "getWords( \"a b c d\", 1, 2, ) // Returns \"b c\"\n"
  1025. "@endtsexample\n\n"
  1026. "@see getWord\n"
  1027. "@see getWordCount\n"
  1028. "@see getFields\n"
  1029. "@see getRecords\n"
  1030. "@ingroup FieldManip" )
  1031. {
  1032. if( endIndex < 0 )
  1033. endIndex = 1000000;
  1034. return Con::getReturnBuffer( StringUnit::getUnits( text, startIndex, endIndex, " \t\n" ) );
  1035. }
  1036. //-----------------------------------------------------------------------------
  1037. DefineConsoleFunction( setWord, const char*, ( const char* text, S32 index, const char* replacement ),,
  1038. "Replace the word in @a text at the given @a index with @a replacement.\n"
  1039. "Words in @a text must be separated by newlines, spaces, and/or tabs.\n"
  1040. "@param text A whitespace-separated list of words.\n"
  1041. "@param index The zero-based index of the word to replace.\n"
  1042. "@param replacement The string with which to replace the word.\n"
  1043. "@return A new string with the word at the given @a index replaced by @a replacement or the original "
  1044. "string if @a index is out of range.\n\n"
  1045. "@tsexample\n"
  1046. "setWord( \"a b c d\", 2, \"f\" ) // Returns \"a b f d\"\n"
  1047. "@endtsexample\n\n"
  1048. "@see getWord\n"
  1049. "@see setField\n"
  1050. "@see setRecord\n"
  1051. "@ingroup FieldManip" )
  1052. {
  1053. return Con::getReturnBuffer( StringUnit::setUnit( text, index, replacement, " \t\n") );
  1054. }
  1055. //-----------------------------------------------------------------------------
  1056. DefineConsoleFunction( removeWord, const char*, ( const char* text, S32 index ),,
  1057. "Remove the word in @a text at the given @a index.\n"
  1058. "Words in @a text must be separated by newlines, spaces, and/or tabs.\n"
  1059. "@param text A whitespace-separated list of words.\n"
  1060. "@param index The zero-based index of the word in @a text.\n"
  1061. "@return A new string with the word at the given index removed or the original string if @a index is "
  1062. "out of range.\n\n"
  1063. "@tsexample\n"
  1064. "removeWord( \"a b c d\", 2 ) // Returns \"a b d\"\n"
  1065. "@endtsexample\n\n"
  1066. "@see removeField\n"
  1067. "@see removeRecord\n"
  1068. "@ingroup FieldManip" )
  1069. {
  1070. return Con::getReturnBuffer( StringUnit::removeUnit( text, index, " \t\n" ) );
  1071. }
  1072. //-----------------------------------------------------------------------------
  1073. DefineConsoleFunction( getWordCount, S32, ( const char* text ),,
  1074. "Return the number of whitespace-separated words in @a text.\n"
  1075. "Words in @a text must be separated by newlines, spaces, and/or tabs.\n"
  1076. "@param text A whitespace-separated list of words.\n"
  1077. "@return The number of whitespace-separated words in @a text.\n\n"
  1078. "@tsexample\n"
  1079. "getWordCount( \"a b c d e\" ) // Returns 5\n"
  1080. "@endtsexample\n\n"
  1081. "@see getFieldCount\n"
  1082. "@see getRecordCount\n"
  1083. "@ingroup FieldManip" )
  1084. {
  1085. return StringUnit::getUnitCount( text, " \t\n" );
  1086. }
  1087. //-----------------------------------------------------------------------------
  1088. DefineConsoleFunction( getField, const char*, ( const char* text, S32 index ),,
  1089. "Extract the field at the given @a index in the newline and/or tab separated list in @a text.\n"
  1090. "Fields in @a text must be separated by newlines and/or tabs.\n"
  1091. "@param text A list of fields separated by newlines and/or tabs.\n"
  1092. "@param index The zero-based index of the field to extract.\n"
  1093. "@return The field at the given index or \"\" if the index is out of range.\n\n"
  1094. "@tsexample\n"
  1095. "getField( \"a b\" TAB \"c d\" TAB \"e f\", 1 ) // Returns \"c d\"\n"
  1096. "@endtsexample\n\n"
  1097. "@see getFields\n"
  1098. "@see getFieldCount\n"
  1099. "@see getWord\n"
  1100. "@see getRecord\n"
  1101. "@ingroup FieldManip" )
  1102. {
  1103. return Con::getReturnBuffer( StringUnit::getUnit( text, index, "\t\n" ) );
  1104. }
  1105. //-----------------------------------------------------------------------------
  1106. DefineConsoleFunction( getFields, const char*, ( const char* text, S32 startIndex, S32 endIndex ), ( -1 ),
  1107. "Extract a range of fields from the given @a startIndex onwards thru @a endIndex.\n"
  1108. "Fields in @a text must be separated by newlines and/or tabs.\n"
  1109. "@param text A list of fields separated by newlines and/or tabs.\n"
  1110. "@param startIndex The zero-based index of the first field to extract from @a text.\n"
  1111. "@param endIndex The zero-based index of the last field to extract from @a text. If this is -1, all fields beginning "
  1112. "with @a startIndex are extracted from @a text.\n"
  1113. "@return A string containing the specified range of fields from @a text or \"\" if @a startIndex "
  1114. "is out of range or greater than @a endIndex.\n\n"
  1115. "@tsexample\n"
  1116. "getFields( \"a b\" TAB \"c d\" TAB \"e f\", 1 ) // Returns \"c d\" TAB \"e f\"\n"
  1117. "@endtsexample\n\n"
  1118. "@see getField\n"
  1119. "@see getFieldCount\n"
  1120. "@see getWords\n"
  1121. "@see getRecords\n"
  1122. "@ingroup FieldManip" )
  1123. {
  1124. if( endIndex < 0 )
  1125. endIndex = 1000000;
  1126. return Con::getReturnBuffer( StringUnit::getUnits( text, startIndex, endIndex, "\t\n" ) );
  1127. }
  1128. //-----------------------------------------------------------------------------
  1129. DefineConsoleFunction( setField, const char*, ( const char* text, S32 index, const char* replacement ),,
  1130. "Replace the field in @a text at the given @a index with @a replacement.\n"
  1131. "Fields in @a text must be separated by newlines and/or tabs.\n"
  1132. "@param text A list of fields separated by newlines and/or tabs.\n"
  1133. "@param index The zero-based index of the field to replace.\n"
  1134. "@param replacement The string with which to replace the field.\n"
  1135. "@return A new string with the field at the given @a index replaced by @a replacement or the original "
  1136. "string if @a index is out of range.\n\n"
  1137. "@tsexample\n"
  1138. "setField( \"a b\" TAB \"c d\" TAB \"e f\", 1, \"g h\" ) // Returns \"a b\" TAB \"g h\" TAB \"e f\"\n"
  1139. "@endtsexample\n\n"
  1140. "@see getField\n"
  1141. "@see setWord\n"
  1142. "@see setRecord\n"
  1143. "@ingroup FieldManip" )
  1144. {
  1145. return Con::getReturnBuffer( StringUnit::setUnit( text, index, replacement, "\t\n" ) );
  1146. }
  1147. //-----------------------------------------------------------------------------
  1148. DefineConsoleFunction( removeField, const char*, ( const char* text, S32 index ),,
  1149. "Remove the field in @a text at the given @a index.\n"
  1150. "Fields in @a text must be separated by newlines and/or tabs.\n"
  1151. "@param text A list of fields separated by newlines and/or tabs.\n"
  1152. "@param index The zero-based index of the field in @a text.\n"
  1153. "@return A new string with the field at the given index removed or the original string if @a index is "
  1154. "out of range.\n\n"
  1155. "@tsexample\n"
  1156. "removeField( \"a b\" TAB \"c d\" TAB \"e f\", 1 ) // Returns \"a b\" TAB \"e f\"\n"
  1157. "@endtsexample\n\n"
  1158. "@see removeWord\n"
  1159. "@see removeRecord\n"
  1160. "@ingroup FieldManip" )
  1161. {
  1162. return Con::getReturnBuffer( StringUnit::removeUnit( text, index, "\t\n" ) );
  1163. }
  1164. //-----------------------------------------------------------------------------
  1165. DefineConsoleFunction( getFieldCount, S32, ( const char* text ),,
  1166. "Return the number of newline and/or tab separated fields in @a text.\n"
  1167. "@param text A list of fields separated by newlines and/or tabs.\n"
  1168. "@return The number of newline and/or tab sepearated elements in @a text.\n\n"
  1169. "@tsexample\n"
  1170. "getFieldCount( \"a b\" TAB \"c d\" TAB \"e f\" ) // Returns 3\n"
  1171. "@endtsexample\n\n"
  1172. "@see getWordCount\n"
  1173. "@see getRecordCount\n"
  1174. "@ingroup FieldManip" )
  1175. {
  1176. return StringUnit::getUnitCount( text, "\t\n" );
  1177. }
  1178. //-----------------------------------------------------------------------------
  1179. DefineConsoleFunction( getRecord, const char*, ( const char* text, S32 index ),,
  1180. "Extract the record at the given @a index in the newline-separated list in @a text.\n"
  1181. "Records in @a text must be separated by newlines.\n"
  1182. "@param text A list of records separated by newlines.\n"
  1183. "@param index The zero-based index of the record to extract.\n"
  1184. "@return The record at the given index or \"\" if @a index is out of range.\n\n"
  1185. "@tsexample\n"
  1186. "getRecord( \"a b\" NL \"c d\" NL \"e f\", 1 ) // Returns \"c d\"\n"
  1187. "@endtsexample\n\n"
  1188. "@see getRecords\n"
  1189. "@see getRecordCount\n"
  1190. "@see getWord\n"
  1191. "@see getField\n"
  1192. "@ingroup FieldManip" )
  1193. {
  1194. return Con::getReturnBuffer( StringUnit::getUnit( text, index, "\n" ) );
  1195. }
  1196. //-----------------------------------------------------------------------------
  1197. DefineConsoleFunction( getRecords, const char*, ( const char* text, S32 startIndex, S32 endIndex ), ( -1 ),
  1198. "Extract a range of records from the given @a startIndex onwards thru @a endIndex.\n"
  1199. "Records in @a text must be separated by newlines.\n"
  1200. "@param text A list of records separated by newlines.\n"
  1201. "@param startIndex The zero-based index of the first record to extract from @a text.\n"
  1202. "@param endIndex The zero-based index of the last record to extract from @a text. If this is -1, all records beginning "
  1203. "with @a startIndex are extracted from @a text.\n"
  1204. "@return A string containing the specified range of records from @a text or \"\" if @a startIndex "
  1205. "is out of range or greater than @a endIndex.\n\n"
  1206. "@tsexample\n"
  1207. "getRecords( \"a b\" NL \"c d\" NL \"e f\", 1 ) // Returns \"c d\" NL \"e f\"\n"
  1208. "@endtsexample\n\n"
  1209. "@see getRecord\n"
  1210. "@see getRecordCount\n"
  1211. "@see getWords\n"
  1212. "@see getFields\n"
  1213. "@ingroup FieldManip" )
  1214. {
  1215. if( endIndex < 0 )
  1216. endIndex = 1000000;
  1217. return Con::getReturnBuffer( StringUnit::getUnits( text, startIndex, endIndex, "\n" ) );
  1218. }
  1219. //-----------------------------------------------------------------------------
  1220. DefineConsoleFunction( setRecord, const char*, ( const char* text, S32 index, const char* replacement ),,
  1221. "Replace the record in @a text at the given @a index with @a replacement.\n"
  1222. "Records in @a text must be separated by newlines.\n"
  1223. "@param text A list of records separated by newlines.\n"
  1224. "@param index The zero-based index of the record to replace.\n"
  1225. "@param replacement The string with which to replace the record.\n"
  1226. "@return A new string with the record at the given @a index replaced by @a replacement or the original "
  1227. "string if @a index is out of range.\n\n"
  1228. "@tsexample\n"
  1229. "setRecord( \"a b\" NL \"c d\" NL \"e f\", 1, \"g h\" ) // Returns \"a b\" NL \"g h\" NL \"e f\"\n"
  1230. "@endtsexample\n\n"
  1231. "@see getRecord\n"
  1232. "@see setWord\n"
  1233. "@see setField\n"
  1234. "@ingroup FieldManip" )
  1235. {
  1236. return Con::getReturnBuffer( StringUnit::setUnit( text, index, replacement, "\n" ) );
  1237. }
  1238. //-----------------------------------------------------------------------------
  1239. DefineConsoleFunction( removeRecord, const char*, ( const char* text, S32 index ),,
  1240. "Remove the record in @a text at the given @a index.\n"
  1241. "Records in @a text must be separated by newlines.\n"
  1242. "@param text A list of records separated by newlines.\n"
  1243. "@param index The zero-based index of the record in @a text.\n"
  1244. "@return A new string with the record at the given @a index removed or the original string if @a index is "
  1245. "out of range.\n\n"
  1246. "@tsexample\n"
  1247. "removeRecord( \"a b\" NL \"c d\" NL \"e f\", 1 ) // Returns \"a b\" NL \"e f\"\n"
  1248. "@endtsexample\n\n"
  1249. "@see removeWord\n"
  1250. "@see removeField\n"
  1251. "@ingroup FieldManip" )
  1252. {
  1253. return Con::getReturnBuffer( StringUnit::removeUnit( text, index, "\n" ) );
  1254. }
  1255. //-----------------------------------------------------------------------------
  1256. DefineConsoleFunction( getRecordCount, S32, ( const char* text ),,
  1257. "Return the number of newline-separated records in @a text.\n"
  1258. "@param text A list of records separated by newlines.\n"
  1259. "@return The number of newline-sepearated elements in @a text.\n\n"
  1260. "@tsexample\n"
  1261. "getRecordCount( \"a b\" NL \"c d\" NL \"e f\" ) // Returns 3\n"
  1262. "@endtsexample\n\n"
  1263. "@see getWordCount\n"
  1264. "@see getFieldCount\n"
  1265. "@ingroup FieldManip" )
  1266. {
  1267. return StringUnit::getUnitCount( text, "\n" );
  1268. }
  1269. //-----------------------------------------------------------------------------
  1270. DefineConsoleFunction( firstWord, const char*, ( const char* text ),,
  1271. "Return the first word in @a text.\n"
  1272. "@param text A list of words separated by newlines, spaces, and/or tabs.\n"
  1273. "@return The word at index 0 in @a text or \"\" if @a text is empty.\n\n"
  1274. "@note This is equal to \n"
  1275. "@tsexample_nopar\n"
  1276. "getWord( text, 0 )\n"
  1277. "@endtsexample\n\n"
  1278. "@see getWord\n"
  1279. "@ingroup FieldManip" )
  1280. {
  1281. return Con::getReturnBuffer( StringUnit::getUnit( text, 0, " \t\n" ) );
  1282. }
  1283. //-----------------------------------------------------------------------------
  1284. DefineConsoleFunction( restWords, const char*, ( const char* text ),,
  1285. "Return all but the first word in @a text.\n"
  1286. "@param text A list of words separated by newlines, spaces, and/or tabs.\n"
  1287. "@return @a text with the first word removed.\n\n"
  1288. "@note This is equal to \n"
  1289. "@tsexample_nopar\n"
  1290. "getWords( text, 1 )\n"
  1291. "@endtsexample\n\n"
  1292. "@see getWords\n"
  1293. "@ingroup FieldManip" )
  1294. {
  1295. const char* ptr = text;
  1296. while( *ptr && *ptr != ' ' && *ptr != '\t' && *ptr != '\n' )
  1297. ptr ++;
  1298. // Skip separator.
  1299. if( *ptr )
  1300. ptr ++;
  1301. return Con::getReturnBuffer( ptr );
  1302. }
  1303. //-----------------------------------------------------------------------------
  1304. static bool isInSet(char c, const char *set)
  1305. {
  1306. if (set)
  1307. while (*set)
  1308. if (c == *set++)
  1309. return true;
  1310. return false;
  1311. }
  1312. DefineConsoleFunction( nextToken, const char*, ( const char* str1, const char* token, const char* delim), , "( string str, string token, string delimiters ) "
  1313. "Tokenize a string using a set of delimiting characters.\n"
  1314. "This function first skips all leading charaters in @a str that are contained in @a delimiters. "
  1315. "From that position, it then scans for the next character in @a str that is contained in @a delimiters and stores all characters "
  1316. "from the starting position up to the first delimiter in a variable in the current scope called @a token. Finally, it "
  1317. "skips all characters in @a delimiters after the token and then returns the remaining string contents in @a str.\n\n"
  1318. "To scan out all tokens in a string, call this function repeatedly by passing the result it returns each time as the new @a str "
  1319. "until the function returns \"\".\n\n"
  1320. "@param str A string.\n"
  1321. "@param token The name of the variable in which to store the current token. This variable is set in the "
  1322. "scope in which nextToken is called.\n"
  1323. "@param delimiters A string of characters. Each character is considered a delimiter.\n"
  1324. "@return The remainder of @a str after the token has been parsed out or \"\" if no more tokens were found in @a str.\n\n"
  1325. "@tsexample\n"
  1326. "// Prints:\n"
  1327. "// a\n"
  1328. "// b\n"
  1329. "// c\n"
  1330. "%str = \"a b c\";\n"
  1331. "while ( %str !$= \"\" )\n"
  1332. "{\n"
  1333. " // First time, stores \"a\" in the variable %token and sets %str to \"b c\".\n"
  1334. " %str = nextToken( %str, \"token\", \" \" );\n"
  1335. " echo( %token );\n"
  1336. "}\n"
  1337. "@endtsexample\n\n"
  1338. "@ingroup Strings" )
  1339. {
  1340. char buffer[4096];
  1341. dStrncpy(buffer, str1, 4096);
  1342. char *str = buffer;
  1343. if( str[0] )
  1344. {
  1345. // skip over any characters that are a member of delim
  1346. // no need for special '\0' check since it can never be in delim
  1347. while (isInSet(*str, delim))
  1348. str++;
  1349. // skip over any characters that are NOT a member of delim
  1350. const char *tmp = str;
  1351. while (*str && !isInSet(*str, delim))
  1352. str++;
  1353. // terminate the token
  1354. if (*str)
  1355. *str++ = 0;
  1356. // set local variable if inside a function
  1357. if (gEvalState.getStackDepth() > 0 &&
  1358. gEvalState.getCurrentFrame().scopeName)
  1359. Con::setLocalVariable(token,tmp);
  1360. else
  1361. Con::setVariable(token,tmp);
  1362. // advance str past the 'delim space'
  1363. while (isInSet(*str, delim))
  1364. str++;
  1365. }
  1366. U32 returnLen = dStrlen(str)+1;
  1367. char *ret = Con::getReturnBuffer(returnLen);
  1368. dStrncpy(ret, str, returnLen);
  1369. return ret;
  1370. }
  1371. //=============================================================================
  1372. // Tagged Strings.
  1373. //=============================================================================
  1374. // MARK: ---- Tagged Strings ----
  1375. //-----------------------------------------------------------------------------
  1376. DefineEngineFunction( detag, const char*, ( const char* str ),,
  1377. "@brief Returns the string from a tag string.\n\n"
  1378. "Should only be used within the context of a function that receives a tagged "
  1379. "string, and is not meant to be used outside of this context. Use getTaggedString() "
  1380. "to convert a tagged string ID back into a regular string at any time.\n\n"
  1381. "@tsexample\n"
  1382. "// From scripts/client/message.cs\n"
  1383. "function clientCmdChatMessage(%sender, %voice, %pitch, %msgString, %a1, %a2, %a3, %a4, %a5, %a6, %a7, %a8, %a9, %a10)\n"
  1384. "{\n"
  1385. " onChatMessage(detag(%msgString), %voice, %pitch);\n"
  1386. "}\n"
  1387. "@endtsexample\n\n"
  1388. "@see \\ref syntaxDataTypes under Tagged %Strings\n"
  1389. "@see getTag()\n"
  1390. "@see getTaggedString()\n"
  1391. "@ingroup Networking")
  1392. {
  1393. if( str[ 0 ] == StringTagPrefixByte )
  1394. {
  1395. const char* word = dStrchr( str, ' ' );
  1396. if( word == NULL )
  1397. return "";
  1398. char* ret = Con::getReturnBuffer( dStrlen( word + 1 ) + 1 );
  1399. dStrcpy( ret, word + 1 );
  1400. return ret;
  1401. }
  1402. else
  1403. return str;
  1404. }
  1405. DefineConsoleFunction( getTag, const char*, ( const char* textTagString ), , "( string textTagString ) "
  1406. "@brief Extracts the tag from a tagged string\n\n"
  1407. "Should only be used within the context of a function that receives a tagged "
  1408. "string, and is not meant to be used outside of this context.\n\n"
  1409. "@param textTagString The tagged string to extract.\n"
  1410. "@returns The tag ID of the string.\n"
  1411. "@see \\ref syntaxDataTypes under Tagged %Strings\n"
  1412. "@see detag()\n"
  1413. "@ingroup Networking")
  1414. {
  1415. if(textTagString[0] == StringTagPrefixByte)
  1416. {
  1417. const char * space = dStrchr(textTagString, ' ');
  1418. U64 len;
  1419. if(space)
  1420. len = space - textTagString;
  1421. else
  1422. len = dStrlen(textTagString) + 1;
  1423. char * ret = Con::getReturnBuffer(len);
  1424. dStrncpy(ret, textTagString + 1, len - 1);
  1425. ret[len - 1] = 0;
  1426. return(ret);
  1427. }
  1428. else
  1429. return(textTagString);
  1430. }
  1431. //=============================================================================
  1432. // Output.
  1433. //=============================================================================
  1434. // MARK: ---- Output ----
  1435. //-----------------------------------------------------------------------------
  1436. ConsoleFunction( echo, void, 2, 0, "( string message... ) "
  1437. "@brief Logs a message to the console.\n\n"
  1438. "Concatenates all given arguments to a single string and prints the string to the console. "
  1439. "A newline is added automatically after the text.\n\n"
  1440. "@param message Any number of string arguments.\n\n"
  1441. "@ingroup Logging" )
  1442. {
  1443. U32 len = 0;
  1444. S32 i;
  1445. for(i = 1; i < argc; i++)
  1446. len += dStrlen(argv[i]);
  1447. char *ret = Con::getReturnBuffer(len + 1);
  1448. ret[0] = 0;
  1449. for(i = 1; i < argc; i++)
  1450. dStrcat(ret, argv[i]);
  1451. Con::printf("%s", ret);
  1452. ret[0] = 0;
  1453. }
  1454. //-----------------------------------------------------------------------------
  1455. ConsoleFunction( warn, void, 2, 0, "( string message... ) "
  1456. "@brief Logs a warning message to the console.\n\n"
  1457. "Concatenates all given arguments to a single string and prints the string to the console as a warning "
  1458. "message (in the in-game console, these will show up using a turquoise font by default). "
  1459. "A newline is added automatically after the text.\n\n"
  1460. "@param message Any number of string arguments.\n\n"
  1461. "@ingroup Logging" )
  1462. {
  1463. U32 len = 0;
  1464. S32 i;
  1465. for(i = 1; i < argc; i++)
  1466. len += dStrlen(argv[i]);
  1467. char *ret = Con::getReturnBuffer(len + 1);
  1468. ret[0] = 0;
  1469. for(i = 1; i < argc; i++)
  1470. dStrcat(ret, argv[i]);
  1471. Con::warnf(ConsoleLogEntry::General, "%s", ret);
  1472. ret[0] = 0;
  1473. }
  1474. //-----------------------------------------------------------------------------
  1475. ConsoleFunction( error, void, 2, 0, "( string message... ) "
  1476. "@brief Logs an error message to the console.\n\n"
  1477. "Concatenates all given arguments to a single string and prints the string to the console as an error "
  1478. "message (in the in-game console, these will show up using a red font by default). "
  1479. "A newline is added automatically after the text.\n\n"
  1480. "@param message Any number of string arguments.\n\n"
  1481. "@ingroup Logging" )
  1482. {
  1483. U32 len = 0;
  1484. S32 i;
  1485. for(i = 1; i < argc; i++)
  1486. len += dStrlen(argv[i]);
  1487. char *ret = Con::getReturnBuffer(len + 1);
  1488. ret[0] = 0;
  1489. for(i = 1; i < argc; i++)
  1490. dStrcat(ret, argv[i]);
  1491. Con::errorf(ConsoleLogEntry::General, "%s", ret);
  1492. ret[0] = 0;
  1493. }
  1494. //-----------------------------------------------------------------------------
  1495. DefineEngineFunction( debugv, void, ( const char* variableName ),,
  1496. "@brief Logs the value of the given variable to the console.\n\n"
  1497. "Prints a string of the form \"<variableName> = <variable value>\" to the console.\n\n"
  1498. "@param variableName Name of the local or global variable to print.\n\n"
  1499. "@tsexample\n"
  1500. "%var = 1;\n"
  1501. "debugv( \"%var\" ); // Prints \"%var = 1\"\n"
  1502. "@endtsexample\n\n"
  1503. "@ingroup Debugging" )
  1504. {
  1505. if( variableName[ 0 ] == '%' )
  1506. Con::errorf( "%s = %s", variableName, Con::getLocalVariable( variableName ) );
  1507. else
  1508. Con::errorf( "%s = %s", variableName, Con::getVariable( variableName ) );
  1509. }
  1510. //-----------------------------------------------------------------------------
  1511. DefineConsoleFunction( expandEscape, const char*, ( const char* text ),,
  1512. "@brief Replace all characters in @a text that need to be escaped for the string to be a valid string literal with their "
  1513. "respective escape sequences.\n\n"
  1514. "All characters in @a text that cannot appear in a string literal will be replaced by an escape sequence (\\\\n, \\\\t, etc).\n\n"
  1515. "The primary use of this function is for converting strings suitable for being passed as string literals "
  1516. "to the TorqueScript compiler.\n\n"
  1517. "@param text A string\n"
  1518. "@return A duplicate of the text parameter with all unescaped characters that cannot appear in string literals replaced by their respective "
  1519. "escape sequences.\n\n"
  1520. "@tsxample\n"
  1521. "expandEscape( \"str\" NL \"ing\" ) // Returns \"str\\ning\".\n"
  1522. "@endtsxample\n\n"
  1523. "@see collapseEscape\n"
  1524. "@ingroup Strings")
  1525. {
  1526. char* ret = Con::getReturnBuffer(dStrlen( text ) * 2 + 1 ); // worst case situation
  1527. expandEscape( ret, text );
  1528. return ret;
  1529. }
  1530. //-----------------------------------------------------------------------------
  1531. DefineConsoleFunction( collapseEscape, const char*, ( const char* text ),,
  1532. "Replace all escape sequences in @a text with their respective character codes.\n\n"
  1533. "This function replaces all escape sequences (\\\\n, \\\\t, etc) in the given string "
  1534. "with the respective characters they represent.\n\n"
  1535. "The primary use of this function is for converting strings from their literal form into "
  1536. "their compiled/translated form, as is normally done by the TorqueScript compiler.\n\n"
  1537. "@param text A string.\n"
  1538. "@return A duplicate of @a text with all escape sequences replaced by their respective character codes.\n\n"
  1539. "@tsexample\n"
  1540. "// Print:\n"
  1541. "//\n"
  1542. "// str\n"
  1543. "// ing\n"
  1544. "//\n"
  1545. "// to the console. Note how the backslash in the string must be escaped here\n"
  1546. "// in order to prevent the TorqueScript compiler from collapsing the escape\n"
  1547. "// sequence in the resulting string.\n"
  1548. "echo( collapseEscape( \"str\\ning\" ) );\n"
  1549. "@endtsexample\n\n"
  1550. "@see expandEscape\n\n"
  1551. "@ingroup Strings" )
  1552. {
  1553. char* ret = Con::getReturnBuffer( text );
  1554. collapseEscape( ret );
  1555. return ret;
  1556. }
  1557. //-----------------------------------------------------------------------------
  1558. DefineEngineFunction( setLogMode, void, ( S32 mode ),,
  1559. "@brief Determines how log files are written.\n\n"
  1560. "Sets the operational mode of the console logging system.\n\n"
  1561. "@param mode Parameter specifying the logging mode. This can be:\n"
  1562. "- 1: Open and close the console log file for each seperate string of output. This will ensure that all "
  1563. "parts get written out to disk and that no parts remain in intermediate buffers even if the process crashes.\n"
  1564. "- 2: Keep the log file open and write to it continuously. This will make the system operate faster but "
  1565. "if the process crashes, parts of the output may not have been written to disk yet and will be missing from "
  1566. "the log.\n\n"
  1567. "Additionally, when changing the log mode and thus opening a new log file, either of the two mode values may be "
  1568. "combined by binary OR with 0x4 to cause the logging system to flush all console log messages that had already been "
  1569. "issued to the console system into the newly created log file.\n\n"
  1570. "@note Xbox 360 does not support logging to a file. Use Platform::OutputDebugStr in C++ instead."
  1571. "@ingroup Logging" )
  1572. {
  1573. Con::setLogMode( mode );
  1574. }
  1575. //=============================================================================
  1576. // Misc.
  1577. //=============================================================================
  1578. // MARK: ---- Misc ----
  1579. //-----------------------------------------------------------------------------
  1580. DefineConsoleFunction( quit, void, ( ),,
  1581. "Shut down the engine and exit its process.\n"
  1582. "This function cleanly uninitializes the engine and then exits back to the system with a process "
  1583. "exit status indicating a clean exit.\n\n"
  1584. "@see quitWithErrorMessage\n\n"
  1585. "@ingroup Platform" )
  1586. {
  1587. Platform::postQuitMessage(0);
  1588. }
  1589. //-----------------------------------------------------------------------------
  1590. DefineConsoleFunction( realQuit, void, (), , "")
  1591. {
  1592. Platform::postQuitMessage(0);
  1593. }
  1594. //-----------------------------------------------------------------------------
  1595. DefineConsoleFunction( quitWithErrorMessage, void, ( const char* message, S32 status ), (0),
  1596. "Display an error message box showing the given @a message and then shut down the engine and exit its process.\n"
  1597. "This function cleanly uninitialized the engine and then exits back to the system with a process "
  1598. "exit status indicating an error.\n\n"
  1599. "@param message The message to log to the console and show in an error message box.\n"
  1600. "@param status The status code to return to the OS.\n\n"
  1601. "@see quit\n\n"
  1602. "@ingroup Platform" )
  1603. {
  1604. Con::errorf( message );
  1605. Platform::AlertOK( "Error", message );
  1606. // [rene 03/30/10] This was previously using forceShutdown which is a bad thing
  1607. // as the script code should not be allowed to pretty much hard-crash the engine
  1608. // and prevent proper shutdown. Changed this to use postQuitMessage.
  1609. Platform::postQuitMessage( status );
  1610. }
  1611. //-----------------------------------------------------------------------------
  1612. DefineConsoleFunction( quitWithStatus, void, ( S32 status ), (0),
  1613. "Shut down the engine and exit its process.\n"
  1614. "This function cleanly uninitializes the engine and then exits back to the system with a given "
  1615. "return status code.\n\n"
  1616. "@param status The status code to return to the OS.\n\n"
  1617. "@see quitWithErrorMessage\n\n"
  1618. "@ingroup Platform" )
  1619. {
  1620. Platform::postQuitMessage(status);
  1621. }
  1622. //-----------------------------------------------------------------------------
  1623. DefineEngineFunction( gotoWebPage, void, ( const char* address ),,
  1624. "Open the given URL or file in the user's web browser.\n\n"
  1625. "@param address The address to open. If this is not prefixed by a protocol specifier (\"...://\"), then "
  1626. "the function checks whether the address refers to a file or directory and if so, prepends \"file://\" "
  1627. "to @a adress; if the file check fails, \"http://\" is prepended to @a address.\n\n"
  1628. "@tsexample\n"
  1629. "gotoWebPage( \"http://www.garagegames.com\" );\n"
  1630. "@endtsexample\n\n"
  1631. "@ingroup Platform" )
  1632. {
  1633. // If there's a protocol prefix in the address, just invoke
  1634. // the browser on the given address.
  1635. char* protocolSep = dStrstr( address,"://");
  1636. if( protocolSep != NULL )
  1637. {
  1638. Platform::openWebBrowser( address );
  1639. return;
  1640. }
  1641. // If we don't see a protocol seperator, then we know that some bullethead
  1642. // sent us a bad url. We'll first check to see if a file inside the sandbox
  1643. // with that name exists, then we'll just glom "http://" onto the front of
  1644. // the bogus url, and hope for the best.
  1645. String addr;
  1646. if( Platform::isFile( address ) || Platform::isDirectory( address ) )
  1647. {
  1648. #ifdef TORQUE2D_TOOLS_FIXME
  1649. addr = String::ToString( "file://%s", address );
  1650. #else
  1651. addr = String::ToString( "file://%s/%s", Platform::getCurrentDirectory(), address );
  1652. #endif
  1653. }
  1654. else
  1655. addr = String::ToString( "http://%s", address );
  1656. Platform::openWebBrowser( addr );
  1657. return;
  1658. }
  1659. //-----------------------------------------------------------------------------
  1660. DefineEngineFunction( displaySplashWindow, bool, (const char* path), ("art/gui/splash.bmp"),
  1661. "Display a startup splash window suitable for showing while the engine still starts up.\n\n"
  1662. "@note This is currently only implemented on Windows.\n\n"
  1663. "@return True if the splash window could be successfully initialized.\n\n"
  1664. "@ingroup Platform" )
  1665. {
  1666. return Platform::displaySplashWindow(path);
  1667. }
  1668. DefineEngineFunction( closeSplashWindow, void, (),,
  1669. "Close our startup splash window.\n\n"
  1670. "@note This is currently only implemented on Windows.\n\n"
  1671. "@ingroup Platform" )
  1672. {
  1673. Platform::closeSplashWindow();
  1674. }
  1675. //-----------------------------------------------------------------------------
  1676. DefineEngineFunction( getWebDeployment, bool, (),,
  1677. "Test whether Torque is running in web-deployment mode.\n"
  1678. "In this mode, Torque will usually run within a browser and certain restrictions apply (e.g. Torque will not "
  1679. "be able to enter fullscreen exclusive mode).\n"
  1680. "@return True if Torque is running in web-deployment mode.\n"
  1681. "@ingroup Platform" )
  1682. {
  1683. return Platform::getWebDeployment();
  1684. }
  1685. //-----------------------------------------------------------------------------
  1686. DefineEngineFunction( countBits, S32, ( S32 v ),,
  1687. "Count the number of bits that are set in the given 32 bit integer.\n"
  1688. "@param v An integer value.\n\n"
  1689. "@return The number of bits that are set in @a v.\n\n"
  1690. "@ingroup Utilities" )
  1691. {
  1692. S32 c = 0;
  1693. // from
  1694. // http://graphics.stanford.edu/~seander/bithacks.html
  1695. // for at most 32-bit values in v:
  1696. c = ((v & 0xfff) * 0x1001001001001ULL & 0x84210842108421ULL) % 0x1f;
  1697. c += (((v & 0xfff000) >> 12) * 0x1001001001001ULL & 0x84210842108421ULL) %
  1698. 0x1f;
  1699. c += ((v >> 24) * 0x1001001001001ULL & 0x84210842108421ULL) % 0x1f;
  1700. #ifndef TORQUE_SHIPPING
  1701. // since the above isn't very obvious, for debugging compute the count in a more
  1702. // traditional way and assert if it is different
  1703. {
  1704. S32 c2 = 0;
  1705. S32 v2 = v;
  1706. for (c2 = 0; v2; v2 >>= 1)
  1707. {
  1708. c2 += v2 & 1;
  1709. }
  1710. if (c2 != c)
  1711. Con::errorf("countBits: Uh oh bit count mismatch");
  1712. AssertFatal(c2 == c, "countBits: uh oh, bit count mismatch");
  1713. }
  1714. #endif
  1715. return c;
  1716. }
  1717. //-----------------------------------------------------------------------------
  1718. DefineEngineFunction( generateUUID, Torque::UUID, (),,
  1719. "Generate a new universally unique identifier (UUID).\n\n"
  1720. "@return A newly generated UUID.\n\n"
  1721. "@ingroup Utilities" )
  1722. {
  1723. Torque::UUID uuid;
  1724. uuid.generate();
  1725. return uuid;
  1726. }
  1727. //=============================================================================
  1728. // Meta Scripting.
  1729. //=============================================================================
  1730. // MARK: ---- Meta Scripting ----
  1731. //-----------------------------------------------------------------------------
  1732. ConsoleFunction( call, const char *, 2, 0, "( string functionName, string args... ) "
  1733. "Apply the given arguments to the specified global function and return the result of the call.\n\n"
  1734. "@param functionName The name of the function to call. This function must be in the global namespace, i.e. "
  1735. "you cannot call a function in a namespace through #call. Use eval() for that.\n"
  1736. "@return The result of the function call.\n\n"
  1737. "@tsexample\n"
  1738. "function myFunction( %arg )\n"
  1739. "{\n"
  1740. " return ( %arg SPC \"World!\" );\n"
  1741. "}\n"
  1742. "\n"
  1743. "echo( call( \"myFunction\", \"Hello\" ) ); // Prints \"Hello World!\" to the console.\n"
  1744. "@endtsexample\n\n"
  1745. "@ingroup Scripting" )
  1746. {
  1747. return Con::execute( argc - 1, argv + 1 );
  1748. }
  1749. //-----------------------------------------------------------------------------
  1750. static U32 execDepth = 0;
  1751. static U32 journalDepth = 1;
  1752. static StringTableEntry getDSOPath(const char *scriptPath)
  1753. {
  1754. #ifndef TORQUE2D_TOOLS_FIXME
  1755. // [tom, 11/17/2006] Force old behavior for the player. May not want to do this.
  1756. const char *slash = dStrrchr(scriptPath, '/');
  1757. if(slash != NULL)
  1758. return StringTable->insertn(scriptPath, slash - scriptPath, true);
  1759. slash = dStrrchr(scriptPath, ':');
  1760. if(slash != NULL)
  1761. return StringTable->insertn(scriptPath, (slash - scriptPath) + 1, true);
  1762. return "";
  1763. #else
  1764. char relPath[1024], dsoPath[1024];
  1765. bool isPrefs = false;
  1766. // [tom, 11/17/2006] Prefs are handled slightly differently to avoid dso name clashes
  1767. StringTableEntry prefsPath = Platform::getPrefsPath();
  1768. if(dStrnicmp(scriptPath, prefsPath, dStrlen(prefsPath)) == 0)
  1769. {
  1770. relPath[0] = 0;
  1771. isPrefs = true;
  1772. }
  1773. else
  1774. {
  1775. StringTableEntry strippedPath = Platform::stripBasePath(scriptPath);
  1776. dStrcpy(relPath, strippedPath);
  1777. char *slash = dStrrchr(relPath, '/');
  1778. if(slash)
  1779. *slash = 0;
  1780. }
  1781. const char *overridePath;
  1782. if(! isPrefs)
  1783. overridePath = Con::getVariable("$Scripts::OverrideDSOPath");
  1784. else
  1785. overridePath = prefsPath;
  1786. if(overridePath && *overridePath)
  1787. Platform::makeFullPathName(relPath, dsoPath, sizeof(dsoPath), overridePath);
  1788. else
  1789. {
  1790. char t[1024];
  1791. dSprintf(t, sizeof(t), "compiledScripts/%s", relPath);
  1792. Platform::makeFullPathName(t, dsoPath, sizeof(dsoPath), Platform::getPrefsPath());
  1793. }
  1794. return StringTable->insert(dsoPath);
  1795. #endif
  1796. }
  1797. DefineConsoleFunction( getDSOPath, const char*, ( const char* scriptFileName ),,
  1798. "Get the absolute path to the file in which the compiled code for the given script file will be stored.\n"
  1799. "@param scriptFileName %Path to the .cs script file.\n"
  1800. "@return The absolute path to the .dso file for the given script file.\n\n"
  1801. "@note The compiler will store newly compiled DSOs in the prefs path but pre-existing DSOs will be loaded "
  1802. "from the current paths.\n\n"
  1803. "@see compile\n"
  1804. "@see getPrefsPath\n"
  1805. "@ingroup Scripting" )
  1806. {
  1807. Con::expandScriptFilename( scriptFilenameBuffer, sizeof(scriptFilenameBuffer), scriptFileName );
  1808. const char* filename = getDSOPath(scriptFilenameBuffer);
  1809. if(filename == NULL || *filename == 0)
  1810. return "";
  1811. return filename;
  1812. }
  1813. //-----------------------------------------------------------------------------
  1814. DefineEngineFunction( compile, bool, ( const char* fileName, bool overrideNoDSO ), ( false ),
  1815. "Compile a file to bytecode.\n\n"
  1816. "This function will read the TorqueScript code in the specified file, compile it to internal bytecode, and, "
  1817. "if DSO generation is enabled or @a overrideNoDDSO is true, will store the compiled code in a .dso file "
  1818. "in the current DSO path mirrorring the path of @a fileName.\n\n"
  1819. "@param fileName Path to the file to compile to bytecode.\n"
  1820. "@param overrideNoDSO If true, force generation of DSOs even if the engine is compiled to not "
  1821. "generate write compiled code to DSO files.\n\n"
  1822. "@return True if the file was successfully compiled, false if not.\n\n"
  1823. "@note The definitions contained in the given file will not be made available and no code will actually "
  1824. "be executed. Use exec() for that.\n\n"
  1825. "@see getDSOPath\n"
  1826. "@see exec\n"
  1827. "@ingroup Scripting" )
  1828. {
  1829. Con::expandScriptFilename( scriptFilenameBuffer, sizeof( scriptFilenameBuffer ), fileName );
  1830. // Figure out where to put DSOs
  1831. StringTableEntry dsoPath = getDSOPath(scriptFilenameBuffer);
  1832. if(dsoPath && *dsoPath == 0)
  1833. return false;
  1834. // If the script file extention is '.ed.cs' then compile it to a different compiled extention
  1835. bool isEditorScript = false;
  1836. const char *ext = dStrrchr( scriptFilenameBuffer, '.' );
  1837. if( ext && ( dStricmp( ext, ".cs" ) == 0 ) )
  1838. {
  1839. const char* ext2 = ext - 3;
  1840. if( dStricmp( ext2, ".ed.cs" ) == 0 )
  1841. isEditorScript = true;
  1842. }
  1843. else if( ext && ( dStricmp( ext, ".gui" ) == 0 ) )
  1844. {
  1845. const char* ext2 = ext - 3;
  1846. if( dStricmp( ext2, ".ed.gui" ) == 0 )
  1847. isEditorScript = true;
  1848. }
  1849. const char *filenameOnly = dStrrchr(scriptFilenameBuffer, '/');
  1850. if(filenameOnly)
  1851. ++filenameOnly;
  1852. else
  1853. filenameOnly = scriptFilenameBuffer;
  1854. char nameBuffer[512];
  1855. if( isEditorScript )
  1856. dStrcpyl(nameBuffer, sizeof(nameBuffer), dsoPath, "/", filenameOnly, ".edso", NULL);
  1857. else
  1858. dStrcpyl(nameBuffer, sizeof(nameBuffer), dsoPath, "/", filenameOnly, ".dso", NULL);
  1859. void *data = NULL;
  1860. U32 dataSize = 0;
  1861. Torque::FS::ReadFile(scriptFilenameBuffer, data, dataSize, true);
  1862. if(data == NULL)
  1863. {
  1864. Con::errorf(ConsoleLogEntry::Script, "compile: invalid script file %s.", scriptFilenameBuffer);
  1865. return false;
  1866. }
  1867. const char *script = static_cast<const char *>(data);
  1868. #ifdef TORQUE_DEBUG
  1869. Con::printf("Compiling %s...", scriptFilenameBuffer);
  1870. #endif
  1871. CodeBlock *code = new CodeBlock();
  1872. code->compile(nameBuffer, scriptFilenameBuffer, script, overrideNoDSO);
  1873. delete code;
  1874. delete[] script;
  1875. return true;
  1876. }
  1877. //-----------------------------------------------------------------------------
  1878. DefineEngineFunction( exec, bool, ( const char* fileName, bool noCalls, bool journalScript ), ( false, false ),
  1879. "Execute the given script file.\n"
  1880. "@param fileName Path to the file to execute\n"
  1881. "@param noCalls Deprecated\n"
  1882. "@param journalScript Deprecated\n"
  1883. "@return True if the script was successfully executed, false if not.\n\n"
  1884. "@tsexample\n"
  1885. "// Execute the init.cs script file found in the same directory as the current script file.\n"
  1886. "exec( \"./init.cs\" );\n"
  1887. "@endtsexample\n\n"
  1888. "@see compile\n"
  1889. "@see eval\n"
  1890. "@ingroup Scripting" )
  1891. {
  1892. bool journal = false;
  1893. execDepth++;
  1894. if(journalDepth >= execDepth)
  1895. journalDepth = execDepth + 1;
  1896. else
  1897. journal = true;
  1898. bool ret = false;
  1899. if( journalScript && !journal )
  1900. {
  1901. journal = true;
  1902. journalDepth = execDepth;
  1903. }
  1904. // Determine the filename we actually want...
  1905. Con::expandScriptFilename( scriptFilenameBuffer, sizeof( scriptFilenameBuffer ), fileName );
  1906. // since this function expects a script file reference, if it's a .dso
  1907. // lets terminate the string before the dso so it will act like a .cs
  1908. if(dStrEndsWith(scriptFilenameBuffer, ".dso"))
  1909. {
  1910. scriptFilenameBuffer[dStrlen(scriptFilenameBuffer) - dStrlen(".dso")] = '\0';
  1911. }
  1912. // Figure out where to put DSOs
  1913. StringTableEntry dsoPath = getDSOPath(scriptFilenameBuffer);
  1914. const char *ext = dStrrchr(scriptFilenameBuffer, '.');
  1915. if(!ext)
  1916. {
  1917. // We need an extension!
  1918. Con::errorf(ConsoleLogEntry::Script, "exec: invalid script file name %s.", scriptFilenameBuffer);
  1919. execDepth--;
  1920. return false;
  1921. }
  1922. // Check Editor Extensions
  1923. bool isEditorScript = false;
  1924. // If the script file extension is '.ed.cs' then compile it to a different compiled extension
  1925. if( dStricmp( ext, ".cs" ) == 0 )
  1926. {
  1927. const char* ext2 = ext - 3;
  1928. if( dStricmp( ext2, ".ed.cs" ) == 0 )
  1929. isEditorScript = true;
  1930. }
  1931. else if( dStricmp( ext, ".gui" ) == 0 )
  1932. {
  1933. const char* ext2 = ext - 3;
  1934. if( dStricmp( ext2, ".ed.gui" ) == 0 )
  1935. isEditorScript = true;
  1936. }
  1937. StringTableEntry scriptFileName = StringTable->insert(scriptFilenameBuffer);
  1938. #ifndef TORQUE_OS_XENON
  1939. // Is this a file we should compile? (anything in the prefs path should not be compiled)
  1940. StringTableEntry prefsPath = Platform::getPrefsPath();
  1941. bool compiled = dStricmp(ext, ".mis") && !journal && !Con::getBoolVariable("Scripts::ignoreDSOs");
  1942. // [tom, 12/5/2006] stripBasePath() fucks up if the filename is not in the exe
  1943. // path, current directory or prefs path. Thus, getDSOFilename() will also screw
  1944. // up and so this allows the scripts to still load but without a DSO.
  1945. if(Platform::isFullPath(Platform::stripBasePath(scriptFilenameBuffer)))
  1946. compiled = false;
  1947. // [tom, 11/17/2006] It seems to make sense to not compile scripts that are in the
  1948. // prefs directory. However, getDSOPath() can handle this situation and will put
  1949. // the dso along with the script to avoid name clashes with tools/game dsos.
  1950. if( (dsoPath && *dsoPath == 0) || (prefsPath && prefsPath[ 0 ] && dStrnicmp(scriptFileName, prefsPath, dStrlen(prefsPath)) == 0) )
  1951. compiled = false;
  1952. #else
  1953. bool compiled = false; // Don't try to compile things on the 360, ignore DSO's when debugging
  1954. // because PC prefs will screw up stuff like SFX.
  1955. #endif
  1956. // If we're in a journaling mode, then we will read the script
  1957. // from the journal file.
  1958. if(journal && Journal::IsPlaying())
  1959. {
  1960. char fileNameBuf[256];
  1961. bool fileRead = false;
  1962. U32 fileSize;
  1963. Journal::ReadString(fileNameBuf);
  1964. Journal::Read(&fileRead);
  1965. if(!fileRead)
  1966. {
  1967. Con::errorf(ConsoleLogEntry::Script, "Journal script read (failed) for %s", fileNameBuf);
  1968. execDepth--;
  1969. return false;
  1970. }
  1971. Journal::Read(&fileSize);
  1972. char *script = new char[fileSize + 1];
  1973. Journal::Read(fileSize, script);
  1974. script[fileSize] = 0;
  1975. Con::printf("Executing (journal-read) %s.", scriptFileName);
  1976. CodeBlock *newCodeBlock = new CodeBlock();
  1977. newCodeBlock->compileExec(scriptFileName, script, noCalls, 0);
  1978. delete [] script;
  1979. execDepth--;
  1980. return true;
  1981. }
  1982. // Ok, we let's try to load and compile the script.
  1983. Torque::FS::FileNodeRef scriptFile = Torque::FS::GetFileNode(scriptFileName);
  1984. Torque::FS::FileNodeRef dsoFile;
  1985. // ResourceObject *rScr = gResourceManager->find(scriptFileName);
  1986. // ResourceObject *rCom = NULL;
  1987. char nameBuffer[512];
  1988. char* script = NULL;
  1989. U32 version;
  1990. Stream *compiledStream = NULL;
  1991. Torque::Time scriptModifiedTime, dsoModifiedTime;
  1992. // Check here for .edso
  1993. bool edso = false;
  1994. if( dStricmp( ext, ".edso" ) == 0 && scriptFile != NULL )
  1995. {
  1996. edso = true;
  1997. dsoFile = scriptFile;
  1998. scriptFile = NULL;
  1999. dsoModifiedTime = dsoFile->getModifiedTime();
  2000. dStrcpy( nameBuffer, scriptFileName );
  2001. }
  2002. // If we're supposed to be compiling this file, check to see if there's a DSO
  2003. if(compiled && !edso)
  2004. {
  2005. const char *filenameOnly = dStrrchr(scriptFileName, '/');
  2006. if(filenameOnly)
  2007. ++filenameOnly;
  2008. else
  2009. filenameOnly = scriptFileName;
  2010. char pathAndFilename[1024];
  2011. Platform::makeFullPathName(filenameOnly, pathAndFilename, sizeof(pathAndFilename), dsoPath);
  2012. if( isEditorScript )
  2013. dStrcpyl(nameBuffer, sizeof(nameBuffer), pathAndFilename, ".edso", NULL);
  2014. else
  2015. dStrcpyl(nameBuffer, sizeof(nameBuffer), pathAndFilename, ".dso", NULL);
  2016. dsoFile = Torque::FS::GetFileNode(nameBuffer);
  2017. if(scriptFile != NULL)
  2018. scriptModifiedTime = scriptFile->getModifiedTime();
  2019. if(dsoFile != NULL)
  2020. dsoModifiedTime = dsoFile->getModifiedTime();
  2021. }
  2022. // Let's do a sanity check to complain about DSOs in the future.
  2023. //
  2024. // MM: This doesn't seem to be working correctly for now so let's just not issue
  2025. // the warning until someone knows how to resolve it.
  2026. //
  2027. //if(compiled && rCom && rScr && Platform::compareFileTimes(comModifyTime, scrModifyTime) < 0)
  2028. //{
  2029. //Con::warnf("exec: Warning! Found a DSO from the future! (%s)", nameBuffer);
  2030. //}
  2031. // If we had a DSO, let's check to see if we should be reading from it.
  2032. //MGT: fixed bug with dsos not getting recompiled correctly
  2033. //Note: Using Nathan Martin's version from the forums since its easier to read and understand
  2034. if(compiled && dsoFile != NULL && (scriptFile == NULL|| (dsoModifiedTime >= scriptModifiedTime)))
  2035. { //MGT: end
  2036. compiledStream = FileStream::createAndOpen( nameBuffer, Torque::FS::File::Read );
  2037. if (compiledStream)
  2038. {
  2039. // Check the version!
  2040. compiledStream->read(&version);
  2041. if(version != Con::DSOVersion)
  2042. {
  2043. Con::warnf("exec: Found an old DSO (%s, ver %d < %d), ignoring.", nameBuffer, version, Con::DSOVersion);
  2044. delete compiledStream;
  2045. compiledStream = NULL;
  2046. }
  2047. }
  2048. }
  2049. // If we're journalling, let's write some info out.
  2050. if(journal && Journal::IsRecording())
  2051. Journal::WriteString(scriptFileName);
  2052. if(scriptFile != NULL && !compiledStream)
  2053. {
  2054. // If we have source but no compiled version, then we need to compile
  2055. // (and journal as we do so, if that's required).
  2056. void *data;
  2057. U32 dataSize = 0;
  2058. Torque::FS::ReadFile(scriptFileName, data, dataSize, true);
  2059. if(journal && Journal::IsRecording())
  2060. Journal::Write(bool(data != NULL));
  2061. if( data == NULL )
  2062. {
  2063. Con::errorf(ConsoleLogEntry::Script, "exec: invalid script file %s.", scriptFileName);
  2064. execDepth--;
  2065. return false;
  2066. }
  2067. else
  2068. {
  2069. if( !dataSize )
  2070. {
  2071. execDepth --;
  2072. return false;
  2073. }
  2074. script = (char *)data;
  2075. if(journal && Journal::IsRecording())
  2076. {
  2077. Journal::Write(dataSize);
  2078. Journal::Write(dataSize, data);
  2079. }
  2080. }
  2081. #ifndef TORQUE_NO_DSO_GENERATION
  2082. if(compiled)
  2083. {
  2084. // compile this baddie.
  2085. #ifdef TORQUE_DEBUG
  2086. Con::printf("Compiling %s...", scriptFileName);
  2087. #endif
  2088. CodeBlock *code = new CodeBlock();
  2089. code->compile(nameBuffer, scriptFileName, script);
  2090. delete code;
  2091. code = NULL;
  2092. compiledStream = FileStream::createAndOpen( nameBuffer, Torque::FS::File::Read );
  2093. if(compiledStream)
  2094. {
  2095. compiledStream->read(&version);
  2096. }
  2097. else
  2098. {
  2099. // We have to exit out here, as otherwise we get double error reports.
  2100. delete [] script;
  2101. execDepth--;
  2102. return false;
  2103. }
  2104. }
  2105. #endif
  2106. }
  2107. else
  2108. {
  2109. if(journal && Journal::IsRecording())
  2110. Journal::Write(bool(false));
  2111. }
  2112. if(compiledStream)
  2113. {
  2114. // Delete the script object first to limit memory used
  2115. // during recursive execs.
  2116. delete [] script;
  2117. script = 0;
  2118. // We're all compiled, so let's run it.
  2119. #ifdef TORQUE_DEBUG
  2120. Con::printf("Loading compiled script %s.", scriptFileName);
  2121. #endif
  2122. CodeBlock *code = new CodeBlock;
  2123. code->read(scriptFileName, *compiledStream);
  2124. delete compiledStream;
  2125. code->exec(0, scriptFileName, NULL, 0, NULL, noCalls, NULL, 0);
  2126. ret = true;
  2127. }
  2128. else
  2129. if(scriptFile)
  2130. {
  2131. // No compiled script, let's just try executing it
  2132. // directly... this is either a mission file, or maybe
  2133. // we're on a readonly volume.
  2134. #ifdef TORQUE_DEBUG
  2135. Con::printf("Executing %s.", scriptFileName);
  2136. #endif
  2137. CodeBlock *newCodeBlock = new CodeBlock();
  2138. StringTableEntry name = StringTable->insert(scriptFileName);
  2139. newCodeBlock->compileExec(name, script, noCalls, 0);
  2140. ret = true;
  2141. }
  2142. else
  2143. {
  2144. // Don't have anything.
  2145. Con::warnf(ConsoleLogEntry::Script, "Missing file: %s!", scriptFileName);
  2146. ret = false;
  2147. }
  2148. delete [] script;
  2149. execDepth--;
  2150. return ret;
  2151. }
  2152. DefineConsoleFunction( eval, const char*, ( const char* consoleString ), , "eval(consoleString)" )
  2153. {
  2154. return Con::evaluate(consoleString, false, NULL);
  2155. }
  2156. DefineConsoleFunction( getVariable, const char*, ( const char* varName ), , "(string varName)\n"
  2157. "@brief Returns the value of the named variable or an empty string if not found.\n\n"
  2158. "@varName Name of the variable to search for\n"
  2159. "@return Value contained by varName, \"\" if the variable does not exist\n"
  2160. "@ingroup Scripting")
  2161. {
  2162. return Con::getVariable(varName);
  2163. }
  2164. DefineConsoleFunction( setVariable, void, ( const char* varName, const char* value ), , "(string varName, string value)\n"
  2165. "@brief Sets the value of the named variable.\n\n"
  2166. "@param varName Name of the variable to locate\n"
  2167. "@param value New value of the variable\n"
  2168. "@return True if variable was successfully found and set\n"
  2169. "@ingroup Scripting")
  2170. {
  2171. return Con::setVariable(varName, value);
  2172. }
  2173. DefineConsoleFunction( isFunction, bool, ( const char* funcName ), , "(string funcName)"
  2174. "@brief Determines if a function exists or not\n\n"
  2175. "@param funcName String containing name of the function\n"
  2176. "@return True if the function exists, false if not\n"
  2177. "@ingroup Scripting")
  2178. {
  2179. return Con::isFunction(funcName);
  2180. }
  2181. DefineConsoleFunction( getFunctionPackage, const char*, ( const char* funcName ), , "(string funcName)"
  2182. "@brief Provides the name of the package the function belongs to\n\n"
  2183. "@param funcName String containing name of the function\n"
  2184. "@return The name of the function's package\n"
  2185. "@ingroup Packages")
  2186. {
  2187. Namespace::Entry* nse = Namespace::global()->lookup( StringTable->insert( funcName ) );
  2188. if( !nse )
  2189. return "";
  2190. return nse->mPackage;
  2191. }
  2192. DefineConsoleFunction( isMethod, bool, ( const char* nameSpace, const char* method ), , "(string namespace, string method)"
  2193. "@brief Determines if a class/namespace method exists\n\n"
  2194. "@param namespace Class or namespace, such as Player\n"
  2195. "@param method Name of the function to search for\n"
  2196. "@return True if the method exists, false if not\n"
  2197. "@ingroup Scripting\n")
  2198. {
  2199. Namespace* ns = Namespace::find( StringTable->insert( nameSpace ) );
  2200. Namespace::Entry* nse = ns->lookup( StringTable->insert( method ) );
  2201. if( !nse )
  2202. return false;
  2203. return true;
  2204. }
  2205. DefineConsoleFunction( getMethodPackage, const char*, ( const char* nameSpace, const char* method ), , "(string namespace, string method)"
  2206. "@brief Provides the name of the package the method belongs to\n\n"
  2207. "@param namespace Class or namespace, such as Player\n"
  2208. "@param method Name of the funciton to search for\n"
  2209. "@return The name of the method's package\n"
  2210. "@ingroup Packages")
  2211. {
  2212. Namespace* ns = Namespace::find( StringTable->insert( nameSpace ) );
  2213. if( !ns )
  2214. return "";
  2215. Namespace::Entry* nse = ns->lookup( StringTable->insert( method ) );
  2216. if( !nse )
  2217. return "";
  2218. return nse->mPackage;
  2219. }
  2220. DefineConsoleFunction( isDefined, bool, ( const char* varName, const char* varValue ), ("") , "(string varName)"
  2221. "@brief Determines if a variable exists and contains a value\n"
  2222. "@param varName Name of the variable to search for\n"
  2223. "@return True if the variable was defined in script, false if not\n"
  2224. "@tsexample\n"
  2225. "isDefined( \"$myVar\" );\n"
  2226. "@endtsexample\n\n"
  2227. "@ingroup Scripting")
  2228. {
  2229. if(dStrIsEmpty(varName))
  2230. {
  2231. Con::errorf("isDefined() - did you forget to put quotes around the variable name?");
  2232. return false;
  2233. }
  2234. StringTableEntry name = StringTable->insert(varName);
  2235. // Deal with <var>.<value>
  2236. if (dStrchr(name, '.'))
  2237. {
  2238. static char scratchBuffer[4096];
  2239. S32 len = dStrlen(name);
  2240. AssertFatal(len < sizeof(scratchBuffer)-1, "isDefined() - name too long");
  2241. dMemcpy(scratchBuffer, name, len+1);
  2242. char * token = dStrtok(scratchBuffer, ".");
  2243. if (!token || token[0] == '\0')
  2244. return false;
  2245. StringTableEntry objName = StringTable->insert(token);
  2246. // Attempt to find the object
  2247. SimObject * obj = Sim::findObject(objName);
  2248. // If we didn't find the object then we can safely
  2249. // assume that the field variable doesn't exist
  2250. if (!obj)
  2251. return false;
  2252. // Get the name of the field
  2253. token = dStrtok(0, ".\0");
  2254. if (!token)
  2255. return false;
  2256. while (token != NULL)
  2257. {
  2258. StringTableEntry valName = StringTable->insert(token);
  2259. // Store these so we can restore them after we search for the variable
  2260. bool saveModStatic = obj->canModStaticFields();
  2261. bool saveModDyn = obj->canModDynamicFields();
  2262. // Set this so that we can search both static and dynamic fields
  2263. obj->setModStaticFields(true);
  2264. obj->setModDynamicFields(true);
  2265. const char* value = obj->getDataField(valName, 0);
  2266. // Restore our mod flags to be safe
  2267. obj->setModStaticFields(saveModStatic);
  2268. obj->setModDynamicFields(saveModDyn);
  2269. if (!value)
  2270. {
  2271. obj->setDataField(valName, 0, varValue);
  2272. return false;
  2273. }
  2274. else
  2275. {
  2276. // See if we are field on a field
  2277. token = dStrtok(0, ".\0");
  2278. if (token)
  2279. {
  2280. // The previous field must be an object
  2281. obj = Sim::findObject(value);
  2282. if (!obj)
  2283. return false;
  2284. }
  2285. else
  2286. {
  2287. if (dStrlen(value) > 0)
  2288. return true;
  2289. else if (!dStrIsEmpty(varValue))
  2290. {
  2291. obj->setDataField(valName, 0, varValue);
  2292. }
  2293. }
  2294. }
  2295. }
  2296. }
  2297. else if (name[0] == '%')
  2298. {
  2299. // Look up a local variable
  2300. if( gEvalState.getStackDepth() > 0 )
  2301. {
  2302. Dictionary::Entry* ent = gEvalState.getCurrentFrame().lookup(name);
  2303. if (ent)
  2304. return true;
  2305. else if (!dStrIsEmpty(varValue))
  2306. {
  2307. gEvalState.getCurrentFrame().setVariable(name, varValue);
  2308. }
  2309. }
  2310. else
  2311. Con::errorf("%s() - no local variable frame.", __FUNCTION__);
  2312. }
  2313. else if (name[0] == '$')
  2314. {
  2315. // Look up a global value
  2316. Dictionary::Entry* ent = gEvalState.globalVars.lookup(name);
  2317. if (ent)
  2318. return true;
  2319. else if (!dStrIsEmpty(varValue))
  2320. {
  2321. gEvalState.globalVars.setVariable(name, varValue);
  2322. }
  2323. }
  2324. else
  2325. {
  2326. // Is it an object?
  2327. if (dStrcmp(varName, "0") && dStrcmp(varName, "") && (Sim::findObject(varName) != NULL))
  2328. return true;
  2329. else if (!dStrIsEmpty(varValue))
  2330. {
  2331. Con::errorf("%s() - can't assign a value to a variable of the form \"%s\"", __FUNCTION__, varValue);
  2332. }
  2333. }
  2334. return false;
  2335. }
  2336. //-----------------------------------------------------------------------------
  2337. DefineConsoleFunction( isCurrentScriptToolScript, bool, (), , "()"
  2338. "Returns true if the calling script is a tools script.\n"
  2339. "@hide")
  2340. {
  2341. return Con::isCurrentScriptToolScript();
  2342. }
  2343. DefineConsoleFunction( getModNameFromPath, const char *, ( const char* path ), , "(string path)"
  2344. "@brief Attempts to extract a mod directory from path. Returns empty string on failure.\n\n"
  2345. "@param File path of mod folder\n"
  2346. "@note This is no longer relevant in Torque 3D (which does not use mod folders), should be deprecated\n"
  2347. "@internal")
  2348. {
  2349. StringTableEntry modPath = Con::getModNameFromPath(path);
  2350. return modPath ? modPath : "";
  2351. }
  2352. //-----------------------------------------------------------------------------
  2353. DefineConsoleFunction( pushInstantGroup, void, ( String group ),("") , "([group])"
  2354. "@brief Pushes the current $instantGroup on a stack "
  2355. "and sets it to the given value (or clears it).\n\n"
  2356. "@note Currently only used for editors\n"
  2357. "@ingroup Editors\n"
  2358. "@internal")
  2359. {
  2360. if( group.size() > 0 )
  2361. Con::pushInstantGroup( group );
  2362. else
  2363. Con::pushInstantGroup();
  2364. }
  2365. DefineConsoleFunction( popInstantGroup, void, (), , "()"
  2366. "@brief Pop and restore the last setting of $instantGroup off the stack.\n\n"
  2367. "@note Currently only used for editors\n\n"
  2368. "@ingroup Editors\n"
  2369. "@internal")
  2370. {
  2371. Con::popInstantGroup();
  2372. }
  2373. //-----------------------------------------------------------------------------
  2374. DefineConsoleFunction( getPrefsPath, const char *, ( const char* relativeFileName ), (""), "([relativeFileName])"
  2375. "@note Appears to be useless in Torque 3D, should be deprecated\n"
  2376. "@internal")
  2377. {
  2378. const char *filename = Platform::getPrefsPath(relativeFileName);
  2379. if(filename == NULL || *filename == 0)
  2380. return "";
  2381. return filename;
  2382. }
  2383. //-----------------------------------------------------------------------------
  2384. ConsoleFunction( execPrefs, bool, 2, 4, "( string relativeFileName, bool noCalls=false, bool journalScript=false )"
  2385. "@brief Manually execute a special script file that contains game or editor preferences\n\n"
  2386. "@param relativeFileName Name and path to file from project folder\n"
  2387. "@param noCalls Deprecated\n"
  2388. "@param journalScript Deprecated\n"
  2389. "@return True if script was successfully executed\n"
  2390. "@note Appears to be useless in Torque 3D, should be deprecated\n"
  2391. "@ingroup Scripting")
  2392. {
  2393. const char *filename = Platform::getPrefsPath(argv[1]);
  2394. if(filename == NULL || *filename == 0)
  2395. return false;
  2396. // Scripts do this a lot, so we may as well help them out
  2397. if(! Platform::isFile(filename) && ! Torque::FS::IsFile(filename))
  2398. return true;
  2399. argv[0] = "exec";
  2400. argv[1] = filename;
  2401. return dAtob(Con::execute(argc, argv));
  2402. }
  2403. //-----------------------------------------------------------------------------
  2404. DefineConsoleFunction( export, void, ( const char* pattern, const char* filename, bool append ), ( "", false ),
  2405. "Write out the definitions of all global variables matching the given name @a pattern.\n"
  2406. "If @a fileName is not \"\", the variable definitions are written to the specified file. Otherwise the "
  2407. "definitions will be printed to the console.\n\n"
  2408. "The output are valid TorqueScript statements that can be executed to restore the global variable "
  2409. "values.\n\n"
  2410. "@param pattern A global variable name pattern. Must begin with '$'.\n"
  2411. "@param filename %Path of the file to which to write the definitions or \"\" to write the definitions "
  2412. "to the console.\n"
  2413. "@param append If true and @a fileName is not \"\", then the definitions are appended to the specified file. "
  2414. "Otherwise existing contents of the file (if any) will be overwritten.\n\n"
  2415. "@tsexample\n"
  2416. "// Write out all preference variables to a prefs.cs file.\n"
  2417. "export( \"$prefs::*\", \"prefs.cs\" );\n"
  2418. "@endtsexample\n\n"
  2419. "@ingroup Scripting" )
  2420. {
  2421. if( filename && filename[ 0 ] )
  2422. {
  2423. #ifndef TORQUE2D_TOOLS_FIXME
  2424. if(Con::expandScriptFilename(scriptFilenameBuffer, sizeof(scriptFilenameBuffer), filename))
  2425. filename = scriptFilenameBuffer;
  2426. #else
  2427. filename = Platform::getPrefsPath( filename );
  2428. if(filename == NULL || *filename == 0)
  2429. return;
  2430. #endif
  2431. }
  2432. else
  2433. filename = NULL;
  2434. gEvalState.globalVars.exportVariables( pattern, filename, append );
  2435. }
  2436. //-----------------------------------------------------------------------------
  2437. DefineEngineFunction( deleteVariables, void, ( const char* pattern ),,
  2438. "Undefine all global variables matching the given name @a pattern.\n"
  2439. "@param pattern A global variable name pattern. Must begin with '$'.\n"
  2440. "@tsexample\n"
  2441. "// Define a global variable in the \"My\" namespace.\n"
  2442. "$My::Variable = \"value\";\n\n"
  2443. "// Undefine all variable in the \"My\" namespace.\n"
  2444. "deleteVariables( \"$My::*\" );\n"
  2445. "@endtsexample\n\n"
  2446. "@see strIsMatchExpr\n"
  2447. "@ingroup Scripting" )
  2448. {
  2449. gEvalState.globalVars.deleteVariables( pattern );
  2450. }
  2451. //-----------------------------------------------------------------------------
  2452. DefineConsoleFunction( trace, void, ( bool enable ), ( true ),
  2453. "Enable or disable tracing in the script code VM.\n\n"
  2454. "When enabled, the script code runtime will trace the invocation and returns "
  2455. "from all functions that are called and log them to the console. This is helpful in "
  2456. "observing the flow of the script program.\n\n"
  2457. "@param enable New setting for script trace execution, on by default.\n"
  2458. "@ingroup Debugging" )
  2459. {
  2460. gEvalState.traceOn = enable;
  2461. Con::printf( "Console trace %s", gEvalState.traceOn ? "enabled." : "disabled." );
  2462. }
  2463. //-----------------------------------------------------------------------------
  2464. #if defined(TORQUE_DEBUG) || !defined(TORQUE_SHIPPING)
  2465. DefineConsoleFunction( debug, void, (),,
  2466. "Drops the engine into the native C++ debugger.\n\n"
  2467. "This function triggers a debug break and drops the process into the IDE's debugger. If the process is not "
  2468. "running with a debugger attached it will generate a runtime error on most platforms.\n\n"
  2469. "@note This function is not available in shipping builds."
  2470. "@ingroup Debugging" )
  2471. {
  2472. Platform::debugBreak();
  2473. }
  2474. #endif
  2475. //-----------------------------------------------------------------------------
  2476. DefineEngineFunction( isShippingBuild, bool, (),,
  2477. "Test whether the engine has been compiled with TORQUE_SHIPPING, i.e. in a form meant for final release.\n\n"
  2478. "@return True if this is a shipping build; false otherwise.\n\n"
  2479. "@ingroup Platform" )
  2480. {
  2481. #ifdef TORQUE_SHIPPING
  2482. return true;
  2483. #else
  2484. return false;
  2485. #endif
  2486. }
  2487. //-----------------------------------------------------------------------------
  2488. DefineEngineFunction( isDebugBuild, bool, (),,
  2489. "Test whether the engine has been compiled with TORQUE_DEBUG, i.e. if it includes debugging functionality.\n\n"
  2490. "@return True if this is a debug build; false otherwise.\n\n"
  2491. "@ingroup Platform" )
  2492. {
  2493. #ifdef TORQUE_DEBUG
  2494. return true;
  2495. #else
  2496. return false;
  2497. #endif
  2498. }
  2499. //-----------------------------------------------------------------------------
  2500. DefineEngineFunction( isToolBuild, bool, (),,
  2501. "Test whether the engine has been compiled with TORQUE_TOOLS, i.e. if it includes tool-related functionality.\n\n"
  2502. "@return True if this is a tool build; false otherwise.\n\n"
  2503. "@ingroup Platform" )
  2504. {
  2505. #ifdef TORQUE_TOOLS
  2506. return true;
  2507. #else
  2508. return false;
  2509. #endif
  2510. }