十六进制常数=格式错误的数字? [英] Hex constant = malformed number?

查看:206
本文介绍了十六进制常数=格式错误的数字?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个Lua脚本,正在尝试使用十六进制数字(0x ..).如果我使用官方Windows二进制文件在控制台中运行此脚本,则可以正常工作.但是,如果我在我的应用程序(简单的dofile)中运行它,我会得到

I have a Lua script, where I'm trying to use hex 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'

十六进制是什么无关紧要,我总是会收到该错误,好像它不支持它们一样.我正在使用的库是Lua 5.1.4,我尝试了2种不同的库(第一个是我自己编译的库),所以这不应该是问题.

It doesn't matter what the hex is, I always get that error, as if it wouldn't support them. The library I'm using is Lua 5.1.4, and I've tried 2 different ones (the first one being one I've compiled myself), so that shouldn't be the problem.

有人知道这里可能有什么问题吗?

Does anyone have a clue what might be wrong here?

修改: 这不是脚本.无论我做什么,即使文件中没有其他内容,一个简单的"foo = 0xf"也已经触发了错误.

It's not the script. No matter what I do, a simple "foo = 0xf" already triggers the error, even if there's nothing else in the file.

更新:

tonumber("0xf")

这将返回nil,而

tonumber("15")

做得很好.我的库中的十六进制肯定有问题...

work fine. There's definitely something wrong with hex in my libs...

推荐答案

为什么不同编译器中的函数必须不同,为什么?

Why do functions have to be different in different compilers, ...why?

好的,问题在于Lua尝试将数字默认转换为双精度.为此,它使用函数"strtod",该函数带有2个参数,字符串和一个char指针. char指针应该指向解析后的数字 之后的最后一个位置.对于十六进制数字,其含义是在"0"之后的"x".如果不是这种情况,Lua会假设一个错误,并向我们提供了一些不错的错误消息.

Alright, the problem was that Lua tries to convert numbers into double by default. For this it uses the function "strtod", which takes 2 arguments, the string, and a char pointer. The char pointer is supposed to point to the last position after the parsed number. Which for a hex number would mean the 'x', after the '0'. If this isn't the case, Lua assumes an error, and gives us this nice little error message.

我已经使用DMC编译了Lua,因为我需要将库包含在OMF中,并且我假设其他人也使用了DMC.但是,显然DMC的strtod的工作原理与众不同,因为如果指针是十六进制……或任何无效数字,则指针始终指向字符串的开头.

I've compiled Lua using DMC, because I need the lib to be in OMF, and I assume others used DMC as well. But apparently DMC's strtod works differenty, since the pointers always point to the start of the string if it's a hex... or rather any invalid number.

我现在添加了一个小技巧,如果转换为double失败,它将检查x.不漂亮,但暂时可以正常工作.

I've now added a little hack, which checks for the x, if conversion to double failed. Not pretty, but it works fine for now.

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 */

这篇关于十六进制常数=格式错误的数字?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆