Jump to content

[HELP] tonumber result not working


MADD NØG

Recommended Posts

I want to get the Hello information but I only get the nill information, I'm sure I'm doing it wrong can anyone help me?

 

"table": {
        "code_one": 113,
        "code_descriptions": [
            "hello world"
        ],
        "code_two": 0
  
          }
}

 

Server-side

 

fetchRemote("[...]",
	function(data)
		local result = fromJSON(data)
		local code = tonumber(result["table"]["code_one"])
		local descriptions = tonumber(result["table"]["code_descriptions"])
		print(code) -- its work, show 113 
		print(descriptions) -- not working, show nill value
	end,
nil, true)

 

Link to comment

You are converting a string to a number, the value of code_descriptions is a string value and when a string is passed as a parameter to tonumber() it will attempt to convert it to a numerical value, for instance turning the string "2.1" into an integer. When a string cannot be converted, you get nil.

If you want to show the description, you do not need to run tonumber() on result["table"]["code_descriptions"].

fetchRemote("[...]",
    function(data)
        local result = fromJSON(data)
        local code = tonumber(result["table"]["code_one"])
        local descriptions = result["table"]["code_descriptions"]
        print(code) -- Outputs 113
        print(descriptions) -- Should output "hello world"
    end,
nil, true)

 

Edited by Skully
Link to comment

Actually, code_descriptions is neither a string nor a number, it is an array type. Meaning if you want to print its string, you need to add [1] to the variable that holds the array, to get the first (and only) value in that array, or use a for each loop to iterate over all strings in that array if there can conceivably be more than one in the actual data.

tonumber on a string that does not contain a correctly formed number returns nil, which is the case in your original code; also I'm pretty sure fromJSON takes care of returning numbers correctly from a JSON where they're written as number literals rather than strings, so you shouldn't need to use tonumber unless your input data sometimes returns the number within a string.

  • Like 1
  • Thanks 1
Link to comment
12 horas atrás, Addlibs disse:

Na verdade, code_descriptions não é uma string nem um número, é um tipo de array. Ou seja, se você quiser imprimir sua string, você precisa adicionar [1] à variável que contém a matriz, para obter o primeiro (e único) valor nessa matriz, ou usar um for each loop para iterar sobre todas as strings nesse array se puder haver mais de um nos dados reais.

tonumber em uma string que não contém um número formado corretamente retorna nil, que é o caso do seu código original; também tenho certeza que fromJSON cuida de retornar números corretamente de um JSON onde eles são escritos como literais numéricos em vez de strings, então você não precisa usar tonumber a menos que seus dados de entrada às vezes retornem o número dentro de uma string.

Nice, its working now!

Link to comment
  • 1 year later...

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
  • Recently Browsing   0 members

    • No registered users viewing this page.
×
×
  • Create New...