diff options
| author | Roberto Ierusalimschy <roberto@inf.puc-rio.br> | 2013-05-14 13:00:11 -0300 |
|---|---|---|
| committer | Roberto Ierusalimschy <roberto@inf.puc-rio.br> | 2013-05-14 13:00:11 -0300 |
| commit | b5ec26101fa8d875fd7f8daf81f2f727cdddcc30 (patch) | |
| tree | d225baa42d940400dc7741b767d27d1c05d60f28 /lapi.c | |
| parent | 36e8771076705d33261a88a3c144967b1840671a (diff) | |
| download | lua-b5ec26101fa8d875fd7f8daf81f2f727cdddcc30.tar.gz lua-b5ec26101fa8d875fd7f8daf81f2f727cdddcc30.tar.bz2 lua-b5ec26101fa8d875fd7f8daf81f2f727cdddcc30.zip | |
new API function 'lua_cvtonum' to convert a value (number or string)
to a number, following the rules of the language to create integers
or floats
Diffstat (limited to 'lapi.c')
| -rw-r--r-- | lapi.c | 24 |
1 files changed, 23 insertions, 1 deletions
| @@ -1,5 +1,5 @@ | |||
| 1 | /* | 1 | /* |
| 2 | ** $Id: lapi.c,v 2.178 2013/04/29 17:12:50 roberto Exp roberto $ | 2 | ** $Id: lapi.c,v 2.179 2013/05/02 12:37:24 roberto Exp roberto $ |
| 3 | ** Lua API | 3 | ** Lua API |
| 4 | ** See Copyright Notice in lua.h | 4 | ** See Copyright Notice in lua.h |
| 5 | */ | 5 | */ |
| @@ -331,6 +331,28 @@ LUA_API int lua_compare (lua_State *L, int index1, int index2, int op) { | |||
| 331 | } | 331 | } |
| 332 | 332 | ||
| 333 | 333 | ||
| 334 | LUA_API int lua_cvtonum (lua_State *L, int idx) { | ||
| 335 | TValue *o = index2addr(L, idx); | ||
| 336 | if (ttisnumber(o)) return 1; /* already a number? */ | ||
| 337 | else if (!ttisstring(o)) return 0; /* only strings can be converted */ | ||
| 338 | else { | ||
| 339 | lua_Integer i; lua_Number n; | ||
| 340 | const char *s = svalue(o); | ||
| 341 | size_t len = tsvalue(o)->len; | ||
| 342 | if (luaO_str2int(s, len, &i)) { | ||
| 343 | setivalue(o, i); | ||
| 344 | return 1; | ||
| 345 | } | ||
| 346 | else if (luaO_str2d(s, len, &n)) { | ||
| 347 | setivalue(o, i); | ||
| 348 | setnvalue(o, n); | ||
| 349 | return 1; | ||
| 350 | } | ||
| 351 | else return 0; | ||
| 352 | } | ||
| 353 | } | ||
| 354 | |||
| 355 | |||
| 334 | LUA_API lua_Number lua_tonumberx (lua_State *L, int idx, int *pisnum) { | 356 | LUA_API lua_Number lua_tonumberx (lua_State *L, int idx, int *pisnum) { |
| 335 | lua_Number n; | 357 | lua_Number n; |
| 336 | const TValue *o = index2addr(L, idx); | 358 | const TValue *o = index2addr(L, idx); |
