Re: tonumber for char* data, is it possible?`

  • From: Mike Pall <mike-1311@xxxxxxxxxx>
  • To: luajit@xxxxxxxxxxxxx
  • Date: Sat, 16 Nov 2013 18:43:19 +0100

Vladimir Dronnikov wrote:
> Need a fast function to convert a FFI char* data to number.

Well, what kind of number? Integer? Decimal/hex? Floating-point?

> src/lj_strscan.c already contains ready-to-use function:
> `StrScanFmt lj_strscan_scan(const uint8_t *p, TValue *o, uint32_t opt)`
> 
> Wonder is it exposed to userspace, or how it can be done?

It's not really exposed, unless you're willing to allocate a
temporary string, i.e. tonumber(ffi.string(cdata)). Arguably that
mostly negates the performance benefit.

The easiest solution would be to call strtod() or strtol() via the
FFI. Though this means you're at the mercy of the C library wrt.
accuracy and performance.

If you need to scan a pure integer then a simple multiply-and-add
loop is probably the fastest. But I recommend to find out first what
the typical range of numbers will be. Sometimes a little unrolling
can do wonders, e.g. if you mostly scan numbers from 0 to 99.

--Mike

Other related posts: