소스 검색

Merge pull request #47 from zeromus/printf

feature: add a printf function to the string stdlib
Alberto Demichelis 9 년 전
부모
커밋
4f20c881ab
3개의 변경된 파일26개의 추가작업 그리고 4개의 파일을 삭제
  1. 2 2
      doc/source/reference/language/builtin_functions.rst
  2. 10 2
      doc/source/stdlib/stdstringlib.rst
  3. 14 0
      sqstdlib/sqstdstring.cpp

+ 2 - 2
doc/source/reference/language/builtin_functions.rst

@@ -52,7 +52,7 @@ returns the const table of the VM.
 
 .. js:function:: setconsttable(table)
 
-sets the const table of the VM. And returns the previous const table.
+sets the const table of the VM; returns the previous const table.
 
 .. js:function:: assert(exp)
 
@@ -60,7 +60,7 @@ throws an exception if exp is null
 
 .. js:function:: print(x)
 
-prints x in the standard output
+prints x to the standard output
 
 .. js:function:: error(x)
 

+ 10 - 2
doc/source/stdlib/stdstringlib.rst

@@ -18,7 +18,7 @@ Global Symbols
 
     returns `true` if the end of the string `str`  matches a the string `cmp` otherwise returns `false`
 	
-.. js:function:: ecape(str)
+.. js:function:: escape(str)
 
     Returns a string with backslashes before characters that need to be escaped(`\",\a,\b,\t,\n,\v,\f,\r,\\,\",\',\0,\xnn`).
 
@@ -28,10 +28,18 @@ Global Symbols
     The format string follows the same rules as the `printf` family of
     standard C functions( the "*" is not supported). ::
 
-        eg.
+        e.g.
         sq> print(format("%s %d 0x%02X\n","this is a test :",123,10));
         this is a test : 123 0x0A
 
+.. js:function:: printf(formatstr, ...)
+
+    Just like calling `print(format(formatstr` as in the example above, but is more convenient AND more efficient. ::
+
+        e.g.
+        sq> printf("%s %d 0x%02X\n","this is a test :",123,10);
+        this is a test : 123 0x0A
+
 .. js:function:: lstrip(str)
 
     Strips white-space-only characters that might appear at the beginning of the given string

+ 14 - 0
sqstdlib/sqstdstring.cpp

@@ -150,6 +150,19 @@ SQRESULT sqstd_format(HSQUIRRELVM v,SQInteger nformatstringidx,SQInteger *outlen
     return SQ_OK;
 }
 
+static SQInteger _string_printf(HSQUIRRELVM v)
+{
+    SQChar *dest = NULL;
+    SQInteger length = 0;
+    if(SQ_FAILED(sqstd_format(v,2,&length,&dest)))
+        return -1;
+    
+    SQPRINTFUNCTION printfunc = sq_getprintfunc(v);
+    if(printfunc) printfunc(v,dest);
+
+    return 0;
+}
+
 static SQInteger _string_format(HSQUIRRELVM v)
 {
     SQChar *dest = NULL;
@@ -459,6 +472,7 @@ static const SQRegFunction rexobj_funcs[]={
 #define _DECL_FUNC(name,nparams,pmask) {_SC(#name),_string_##name,nparams,pmask}
 static const SQRegFunction stringlib_funcs[]={
     _DECL_FUNC(format,-2,_SC(".s")),
+    _DECL_FUNC(printf,-2,_SC(".s")),
     _DECL_FUNC(strip,2,_SC(".s")),
     _DECL_FUNC(lstrip,2,_SC(".s")),
     _DECL_FUNC(rstrip,2,_SC(".s")),