Hex constant = invalid number?

I have a Lua script where I am trying to use hexadecimal numbers (0x ..). If I run this script in the console, with the official Windows binaries, it works fine. But if I run it in my application (simple dofile), I get

malformed number near '0x1F' 

No matter what hex is, I always get this error as if it did not support them. The library I use is Lua 5.1.4, and I tried 2 different ones (the first one was me that I compiled), so this should not be a problem.

Does anyone know what could be wrong here?

Edit: This is not a script. No matter what I do, a simple "foo = 0xf" already causes an error, even if there is nothing in the file.

Update:

 tonumber("0xf") 

This returns zero, and

 tonumber("15") 

works fine. There is definitely something wrong with hex in my libraries ...

+4
source share
3 answers

Why should functions be different in different compilers ... why?

Well, the problem was that Lua was trying to convert numbers to double by default. To do this, use the strtod function, which takes 2 arguments, a string and a char pointer. The char pointer must point to the last position after the parsed number. Which for a hexadecimal number would mean "x", after "0". If this is not the case, Lua accepts the error and gives us this small little error message.

I compiled Lua using DMC because I need the lib to be in OMF, and I suppose others used DMC. But obviously DMC strtod works differently, since pointers always point to the beginning of a line if it is hexadecimal ... or rather an invalid number.

Now I have added a little hack that checks x if conversion to double fails. Not very, but at the moment everything is fine.

 int luaO_str2d (const char *s, lua_Number *result) { char *endptr; *result = lua_str2number(s, &endptr); /* Hack for DMC */ if (endptr == s) if(*(s+1) == 'x' || *(s+1) == 'X') endptr++; else return 0; /* conversion failed */ 
+3
source

If hex literals don't work for you (although they should), you can always use hex from lua by doing tonumber("fe",16)

+3
source

I ran into this error with lua5.2. Lua 5.1 works great.

0
source

Source: https://habr.com/ru/post/1396821/


All Articles