2016-09-14 74 views
0

我还有一个关于lua的问题。我创建了一种方法来计算一些价格的总量。价格是这种格式:500英镑。所以要将它们转换为我使用string:sub()和tonumber()的数字,但我得到了一些奇怪的结果。这里是我的代码:`String sub not working correctly

function functions.calculateTotalAmount() 
print("calculating total amount") 
saveData.totalAmount = 0 
print("There are " .. #saveData.amounts .. " in the amount file") 
for i=1, #saveData.names do 
    print("SaveData.amounts[" .. i .. "] original = " .. saveData.amounts[i]) 
    print("SaveData.amounts[" .. i .. "] after sub= " .. saveData.amounts[i]:sub(2)) 
    print("totalAmount: " .. saveData.totalAmount) 
    if saveData.income[i] then 
     saveData.totalAmount = saveData.totalAmount + tonumber(saveData.amounts[i]:sub(2)) 
    else 
     saveData.totalAmount = saveData.totalAmount - tonumber(saveData.amounts[i]:sub(2)) 
    end 
end 
totalAmountStr.text = saveData.totalAmount .. " " .. currencyFull 
loadsave.saveTable(saveData, "payMeBackTable.json") 

我打印出来的for循环的一些信息,以确定问题,这是正在打印的内容在第2个打印语句for循环:

16:03:51.452 SaveData.amounts 1原始=¥201

16:03:51.452 SaveData.amounts 1后子= 201

在stackoverflow中看起来很好,但对于¥实际上没有在我的日志中消失,而是用一个奇怪的矩形符号代替。将会有一张附在这篇文章上的印刷文字的图片。 有人看到这里发生了什么? enter image description here

回答

1

不要在这种情况下使用sub作为¥符号可能是一个多字节序列(根据编码) ,所以使用sub(2)你是在中间切割而不是去除它。

改为使用gsub("[^%d%.]+","")删除所有非数字部分。

+0

这对我有用!我认为这个子功能可以和这些角色一起工作,因为它似乎与美元符号一起工作。感谢您的帮助! –

0

string.sub()作品在字节字符串,而不是它的字符。字符串包含Unicode文本时有区别。

如果该号码是在字符串的末尾,以提取它

amount = tonumber(saveData.amounts[i]:match("%d+$")) 
0

Lua字符串是字节的字符串,而不是字符的字符串。 ASCII字符长度为1个字节,但大多数其他字符占用多个字节,因此使用string.sub()不起作用。

有几种标准字节字符(或码点)之间的转换,但迄今为止在网络上最常见的是UTF-8。如果您使用的是Lua 5.3或更高版本,则可以使用新的built-in functions来执行UTF-8操作。例如,采取UTF-8字符串的一个子,你可以这样做:

-- Simple version without bounds-checking. 
function utf8_sub1(s, start_char_idx, end_char_idx) 
    start_byte_idx = utf8.offset(s, start_char_idx) 
    end_byte_idx = utf8.offset(s, end_char_idx + 1) - 1 
    return string.sub(s, start_byte_idx, end_byte_idx) 
end 

-- More robust version with bounds-checking. 
function utf8_sub2(s, start_char_idx, end_char_idx) 
    start_byte_idx = utf8.offset(s, start_char_idx) 
    end_byte_idx = utf8.offset(s, end_char_idx + 1) 
    if start_byte_idx == nil then 
    start_byte_idx = 1 
    end 
    if end_byte_idx == nil then 
    end_byte_idx = -1 
    else 
    end_byte_idx = end_byte_idx - 1 
    end 
    return string.sub(s, start_byte_idx, end_byte_idx) 
end 

s = "¥201" 

print(string.sub(s, 2, 4)) -- an invalid byte sequence 
print(utf8_sub1(s, 2, 4)) -- "201" 
print(utf8_sub2(s, 2, 4)) -- "201" 
print(utf8_sub1(s, 2, 5)) -- throws an error 

如果你没有的Lua 5.3,可以使用UTF-8图书馆像this one代替来实现相同的功能。