Scripting Helpers is winding down operations and is now read-only. More info→
Ad
Log in to vote
0

How to check if a table has more than one value?

Asked by 4 years ago

Is there a way I can check if a table has more than one value? Like for example

local table = {0,0}

check if table has more than 1 value then return true

or check if a table has more than 2 value then return true

if it's more than 2 like 3 then return false

How can I do this?

1 answer

Log in to vote
1
Answered by
BlueTaslem 18071 Moderation Voter Administrator Community Moderator Super Administrator
4 years ago

If your table t is a list, then #t is the number of elements in the list.

print(#{}) --> 0
print(#{"a"}) --> 1
print(#{"a", "b"}) --> 2
print(#{"a", "b", "c"}) --> 3

You can compare the size to one to know if it has more than one element:

print(#{} > 1) --> false
print(#{"a"} > 1) --> false
print(#{"a", "b"} > 1) --> true
print(#{"a", "b", "c"} > 1) --> true

This will only work for lists.

Dictionaries, which use non-whole-number keys, don't get counted by #.

Lists which have nil "holes" in them (like {1, nil, 3}) may or may not count the nils; Lua allows the length of a list like {1, nil, 3} to be either 1 or 3 -- it's better to just not use # on such tables because the result is confusing.

Ad

Answer this question