Home  Contents

string.val

String Core4 Lua Commands

SYNOPSIS

result = string.val(s [, i [, j [, base]]])

DESCRIPTION

Returns the numerical value of the substring s[i], s[i+1], ···, s[j].
The default value for i is 1; the default value for j is the number of characters in s.

The optional argument base can be used to explicitly specify the number base. By default, the decoder will detect the base automatically: If the (sub-)string starts with 0x, the base is 16, if the string starts with 0y, the base is 2, in all other cases the base is 10. Prefix detection is not case sensitive.

If you want to only specify the base without a substring range, the values for i and j must be explicitly passed as nil.

RETURN VALUE

On success, a numerical value. If the substring doesn't decode to a number, returns nil.

NOTES

Generic Lua already supports turning strings into numbers natively. The string.val() described here has three advantages over the built in type coercion:

  • You can specify a substring easily without creating more garbage.
  • The application will not terminate if the data cannot be converted to a number. You just get nil.
  • A number base can be selected.

EXAMPLE

print(string.val("XX42YYYY", 3, 4))
42
print(string.val("A5", nil, nil, 16))
165