lua-users home
lua-l archive

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]


If someone is interested in, this is my luaO_str2d() in lobject.c for 
Lua 4.0a (I guess that Erik's source works in Lua 3.2).
You can use bases from 1 (!) to 26, + and - sign, lower or upper case 
(IE 0x or 0X). You can't use base 24 because I use 0X like 0P for 
hexadecimal numbers. I also changed luaX_lex() in llex.c to accept this 
kind of numbers (but it need to be improved).

Mauro


int luaO_str2d (const char *s, Number *result) {  /* LUA_NUMBER */
  double a = 0.0;
  int point = 0;  /* number of decimal digits */
  int sig;
  while (isspace((unsigned char)*s)) s++;
  sig = 0;
  switch (*s) {
    case '-': sig = 1;  /* go through */
    case '+': s++;
  }
  if (! (isdigit((unsigned char)*s) ||
          (*s == '.' && isdigit((unsigned char)*(s+1)))))
    return 0;  /* not (at least one digit before or after the point) */
/* Start of my extension */
  if (((unsigned char)*s == '0') && isalpha((unsigned char)*(s + 1))) {
    char base, *s2;

    base = toupper((unsigned char)*(s + 1));
    a = strtoul(s + 2, &s2, (base == 'X') ? 16 : (base - 'A' + 1));
    if (*s2 != '\0' || s + 2 == s2) return 0;  /* invalid trailing 
characters? */
    *result = sig ? -a : a;
    return 1;
  }
/* End of my extension */
  while (isdigit((unsigned char)*s))
    a = 10.0*a + (*(s++)-'0');
  if (*s == '.') {
    s++;
    while (isdigit((unsigned char)*s)) {
      a = 10.0*a + (*(s++)-'0');
      point++;
    }
  }
  if (sig) a = -a;
  if (*s == 'e' || *s == 'E') {
    int e = 0;
    s++;
    sig = 0;
    switch (*s) {
      case '-': sig = 1;  /* go through */
      case '+': s++;
    }
    if (!isdigit((unsigned char)*s)) return 0;  /* no digit in the 
exponent? */
    do {
      e = 10*e + (*(s++)-'0');
    } while (isdigit((unsigned char)*s));
    if (sig) e = -e;
    point -= e;
  }
  while (isspace((unsigned char)*s)) s++;
  if (*s != '\0') return 0;  /* invalid trailing characters? */
  if (point != 0) {
    if (point > 0) a /= expten(point);
    else           a *= expten(-point);
  }
  *result = a;
  return 1;
}