Search code examples
stringluasubstringcoronasdk

String sub not working correctly


I've got yet another question about lua. I've created a method to calculate the total amount of some prices. The prices are in this format: £500. So to convert them to numbers I'm using string:sub() and tonumber(), but I'm getting some weird results. Here is my code:`

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")

end

I printed out some info in the for loop to determine the problem and this is what is being printed for the first 2 print statements in the for loop:

16:03:51.452 SaveData.amounts1 original = ¥201

16:03:51.452 SaveData.amounts1 after sub= 201

It looks fine here in stackoverflow but for the the ¥ is actually not gone in my log, instead it is replaced with a weird rectangle symbol. There will be a picture of the printed text attached to this post. Does anyone see what is going on here?enter image description here


Solution

  • Don't use sub in this case as the ¥ sign is likely a multi-byte sequence (depending on the encoding), so using sub(2) you are cutting it in the middle instead of removing it.

    Use gsub("[^%d%.]+","") instead to remove all non-numeric parts.