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

how do i add sub-tables in a table with a script?

Asked by
karbis 50
3 years ago
Edited 3 years ago

im trying to do something like this

if atable[vectorpos] ~= nil then
    print("hey this position isnt taken")
else
    table.insert(atable,1,[vectorpos = vectorpos])
end
-- vector pos is turned into a string for this example

this would require me to make that vectorpos a subtable in a table, how would i do that

(also i mean ["a"] = "a" types)

1 answer

Log in to vote
1
Answered by
imKirda 4491 Moderation Voter Community Moderator
3 years ago
Edited 3 years ago

So from i see from your code you are trying to check if that spot is not taken yet, there are multiple ways of doing it based off the situation.

You can add the vector value into table and then check if the value is in the table (This is what you were trying to do if i'm right) Here is example of it:

local takenVectors = { -- Current positions in the table
    Vector3.new(0, 2, 0),
    Vector3.new(0, 0, 4),
}

local newVector = Vector3.new(0, 2, 0) -- This position is already in a table

for index, takenVector in pairs(takenVectors) do
    if takenVector == newVector then -- If same vector already exists in the table, it will print it out
        print("Spot is taken!")
        break -- Breaks pairs loop to not check anymore
    end
end

If you would like to change specific vector in the table (Like you said something (also i mean ["a"] = "a" types)) you can try this method:

local takenVectors = {}

local newVector = Vector3.new(0, 0, 0)

takenVectors[tostring(newVector)] = newVector -- inserts the vector into table with index

for index, vector in pairs(takenVectors) do
    print(index, vector)
end

--> Output: 0, 0, 0 0, 0, 0

I don't know if this is what you need and i don't know if this is efficient method of indexing but it works atleast and you can access the vector from the table by doing print(takenVectors["0, 0, 0"]).

Ad

Answer this question