So basically, I know that if you use them correctly, you can get a specific number of them I think? I don’t really know. (That’s why I’m asking lol) I want to know how to use them, and what else they can do, or where to put them.
I haven’t done much research because I don’t know what its called other than to call it #. I can’t find any scripts for it, so you will probably have to figure it out cuz that’s the best I can explain it.
# is the ternary operator for the __len metamethod.
The default behavior of the # operator is to return the amount of values in a number indexed table
So when you do this:
local t = {1, 2, 3}
print(#t)
You are actually doing this:
local t = {1, 2, 3}
print(getmetatable(t).__len(t))
Of course Lua obscures this as a high-level programming language.
Additionally, you can override this metamethod to whatever you want.
Maybe you have a Bank class and you want to return the amount of accounts?
local Bank = {}
Bank.__len = function(tbl)
-- magic code
end
Side notes:
Invoking # on strings will return the length of the string.
If the object is not a string, it will use the object’s metamethod.
If the object is a table, it will use the metamethod will the table parameter passed.
A ternary operator is an operator that takes 3 operands, a unary operator takes a single operand. Did you mean the latter? Additionally, __len does not work in Lua 5.1, which Luau is based off of.
No, it just returns the length of a table or string. Tables don’t have children so I assume you mean the values stored, to do that you need to use a for loop.
for i = 1, #table do
print(table[i])
end
The for loop goes from 1 (first index) to #table (last index) and you access the values of the table with the [] operator, where the operator takes the index you want to access.
If you ever need to get the length of a dictionary you can use the following script I wrote.
local function dictionaryLength(dictionary)
local count = 0
for key, value in next, dictionary do
count+= 1
end
return count
end
print(dictionaryLength({a = true, b = false, c = math.huge})) --3