Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if value exists in Lua table

Tags:

json

lua

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?

like image 677
Jaka Kordež Avatar asked May 16 '15 19:05

Jaka Kordež


People also ask

How do you check if a value is in a list Lua?

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.

How can you tell if a table is Lua?

Yes. type() is exactly what you're looking for. The type returned is one of the following: string, number, function, boolean, table or nil.

What does in Do in Lua?

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.


1 Answers

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
like image 190
Yu Hao Avatar answered Oct 29 '22 16:10

Yu Hao