consoleFunctions.cpp 103 KB

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