lua-users home
lua-l archive

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


I had a report that some of my code was failing in the nb_NO-utf8 locale:
Indeed, `tonumber` behaves differently depending on locale:

$ lua -e 'os.setlocale("nb_NO.utf-8") print(tonumber("1.0"))'
nil
$ lua -e 'os.setlocale("nb_NO.utf-8") print(tonumber("1,0"))'
1,0

However it *doesn't* affect lua parsing; which seems to be against the manual.

>From http://www.lua.org/manual/5.3/manual.html#pdf-tonumber
> The conversion of strings can result in integers or floats, according to the lexical conventions
> of Lua (see §3.1). (The string may have leading and trailing spaces and a sign.)

$ lua -e 'os.setlocale("nb_NO.utf-8") print(load([[return 1.0]])())'
1,0
$ lua -e 'os.setlocale("nb_NO.utf-8") print(load([[return 1,0]])())'
1 0

This leaves me with the question of how to deserialise a floating
point number within a lua library (where I can't control the locale of
the application).
Normally I'd write something like:

    local mystring = "some protocol 1.0"
    local version = mystring:match("(%d+%.%d*)") --> version == "1.0"
    version = tonumber(version) --> version == 1.0

Or using lpeg:

    local digit = lpeg.R "09"
    local version_patt = digit^1 * lpeg.P "." * digit^0 / tonumber
    local parser = something * version_patt
    local version = parser:match "some protocol 1.0" --> version == 1.0

But this doesn't work in some locales :(
What do other people do? and is there a good solution?