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
Yes. type() is exactly what you're looking for. The type returned is one of the following: string, number, function, boolean, table or nil.
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.
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.
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.
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.
print(type(elem)) -->table
the type function in Lua returns what datatype it's first parameter is (string)
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