consoleFunctions.cpp 108 KB

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