I am running Lua on ESP8266 Wifi module with NodeMCU firmware. My application is listening on TCP port for JSON requests. When I get the request I parse it using:
jsonRequest = json.decode(request)
So then I can access desired value with:
jsonRequest.object.state
Everything works perfectly until I send an invalid JSON (without "object"). When that happens I get this error: Lua API (attempt to index a nil value) and my program stops with execution.
MY PROBLEM: I would like to check if my table contains that key before accessing, but I can't find a way to do it.
I could do it with pairs function and loop through all keys and check if there is the right one, but that would require lots of code because I have multiple nested objects in my JSON.
Any ideas?
When you have an array-like table, you can check if it contains a certain value by looping through the table. You can use a for..in loop, and the ipairs function to create a generic function. We can use the above in an if conditional to get our result.
Yes. type() is exactly what you're looking for. The type returned is one of the following: string, number, function, boolean, table or nil.
Lua's in is not a function or a variable. It's a part of the syntax for flow control. You can't replace it, you can't copy it, you can't even refer to it. It's rather like parentheses: a syntactic construct which has meaning for how a program is parsed, but which cannot be referred to within the program.
To check if the table jsonRequest
contains the key "object"
, use:
if jsonRequest.object ~= nil then
If the values stored in the table won't be the boolean value false
, you can also use:
if jsonRequest.object then
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With