Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Lua: How to find out if an element is a table instead of a string/number?

Tags:

As the title says, what function or check can I do to find out if a lua element is a table or not?

local elem = {['1'] = test, ['2'] = testtwo}
if (elem is table?) // <== should return true
like image 237
unwise guy Avatar asked Jul 21 '12 03:07

unwise guy


People also ask

How do you check if something is a table in 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.

How do you check if a value is a string Lua?

To check wether a value is a string use type(value) == "string" . To check wether a value can be convertet do a number use tonumber(value) . It will either return a number or nil.

How do I know if a table is empty Lua?

One possibility would be to count the number of elements, by using the metatable "newindex" key. When assigning something not nil , increment the counter (the counter could live in the metatable as well) and when assigning nil , decrement the counter. Testing for empty table would be to test the counter with 0.

How do tables work Lua?

Tables are the only data structure available in Lua that helps us create different types like arrays and dictionaries. Lua uses associative arrays and which can be indexed with not only numbers but also with strings except nil. Tables have no fixed size and can grow based on our need.


2 Answers

In the context of the original question,

local elem = {['1'] = test, ['2'] = testtwo}
if (type(elem) == "table") then
  -- do stuff
else
  -- do other stuff instead
end

Hope this helps.

like image 38
Hugh Avatar answered Sep 22 '22 19:09

Hugh


print(type(elem)) -->table

the type function in Lua returns what datatype it's first parameter is (string)

like image 164
Nathan Avatar answered Sep 23 '22 19:09

Nathan