Take this example
local tab = {
[1] = "A"
[2] = "B"
[3] = "C"
[4] = "D"
}
Does this still count as an array?
Take this example
local tab = {
[1] = "A"
[2] = "B"
[3] = "C"
[4] = "D"
}
Does this still count as an array?
Yes, that’s the equivalent of doing:
local tab = {"A", "B", "C", "D"}
-- each item index is numerical
yes it does count as an array
{
1,
2,
3
}
{
[1] = 1,
[2] = 2,
[3] = 3
}
both of these tables are the same
So if i did this:
local tab = {
[1] = "A"
[2] = "B"
[3] = "C"
[4] = "D"
}
tab[#tab + 1] = "E"
tab[4] = nil
print(tab[4])
it would print “E”?
Wouldn’t you need to use table.insert(tab[#tab + 1] = "E")
?
No, it will print nil
. If you want the values to shift over, you have to use table.remove
.
local tab = {
[1] = "A",
[2] = "B",
[3] = "C",
[4] = "D",
}
table.insert(tab, "E")
table.remove(tab, 4)
print(tab[4])
Curious whats happening here, but yes, if the structure of the keys remains in the pattern 1, 2, 3, 4… it’ll remain as an array.
ipairs and # also work on dictionaries but count up from 1 until they hit a nil value
That would be a syntax error. It’s table.insert(tab, value)
Could you confirm what @HugeCoolboy2007 said about table.remove() being the only way to update the keys automatically?
If you’re removing numeric keys and want to shift everything after it down one index, yes. Combine it with table.find to remove an index by value.
Yes, I still am yet to learn about tables, however I do know adding tables to an existing one needs to use table.insert
. (I do have a bit of table knowlage however.)
just a tip
table.insert is faster
yeah but that does not trigger metamethods iirc
Tables can support this syntax:
tab[key] = value
The way t[#t + 1] works is by adding a new value to the end of the table with the length of t. table.insert is more optimised in Luau since the # method is more expensive, and it also doesn’t fire any metamethods.
So table.insert
is just the better way to go in general?
Unless you’re working with the __newindex metamethod, yes.
I will make sure to study tables, as they seem pretty nice. Would using a table like this be reasonable? (Taken from a preexisting code I made.)
local AllowedRanks = {
1,
2,
3
}
if Player:GetRankInGroup(_Replace) >= AllowedRanks then
Is that better than this?
if Player:GetRankInGroup(_Replace) >= 1 or 2 or 3 then
This code has been taken and edited for the purposes of this comment.
you can’t compare a table with a number
local AllowedRanks = {
1,
2,
3
}
if table.find(AllowedRanks, Player:GetRankInGroup(_Replace)) then
we can make it work with table.find
So but the way I think this would work (correct me if I’m wrong), is it would look through the table, and get the data from which is inside of it, and return it as AllowedRanks.
I recommend making a new topic since this doesn’t have anything to do with the OP