I'm writing a script which rely's a ton on the number of objects in a table to properly tween them, but when a function is called which checks #mytable
, the result it gets is always 0, and despite the fact that the table does have data in it (the script adds a object to the table before it runs said function, so the table must be full), it always returns 0, so if any one knows what the issue is please tell me.
Here is a script which may help diagnose the issue:
local mytable = {} function getIncerement() print(#mytable) --always outputs 0 if #mytable > 1 then return 0.5 else return 0 end end function func(name) local obj --I would put my object here mytable[name] = obj local i = getIncerement() obj.Position = UDim2.new(0,0,i,0) --just pretend obj had a udim2 property end func("abc") wait(1) func("dfg")
Aaaaaaaaaand ya my issue is when the getIncerement()
function is called always #mytable
returns 0, if you can figure out the issue great, because this is threatening the cleanliness of a script of mine.
Thanks ~chabad360
Consult Section 2.5.5 of the Lua 5.1 Reference Manual:
"The length of a table t
is defined to be any integer index n
such thatt[n]
is not nil and t[n+1]
is nil; moreover, if t[1]
is nil, n
can be zero."
The result of the length operator (#
), when applied to a table, will be correct if each integer index from 0 to n (for some value of n) is non-nil.
I propose two possible solutions:
Introduce a new variable (e.g. myTableLength
). Update it manually whenever objects are added or removed from the table. In your func
, you would write myTableLength = myTableLength + 1
.
Use a generic table entry counting function to compute the length:
function tableLength(t) local count = 0 for _ in pairs(t) do count = count + 1 end return count end
This is because your table
is composed in dictionary
format. There are two kinds of tables:
Arrays (Lists)
A table comprised of only numeric keys
(i.e, just having single elements in a table)
Dictionaries (Maps)
A table comprised of manually defined keys
(i.e, assigning variable-like conditions to a value inside the table)
Dictionary (or Map) example
-- "x","y","z" overwrites our numeric keys 1,2,3. local Dictionary = { x = "hello", y = "i am", z = "a dictionary" }
Array (or List) example
-- Nothing overwrites our default numeric keys, therefore they remain 1,2,3, allowing us to use the # operator on the table to return the number of elements. local Array = { "hello", "i am", "an array" }
I would go on, but honestly everything I'd explain here I've already explained in another answer that you may find very useful here:
https://scriptinghelpers.org/questions/25964/what-are-tables#29555