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

Trying to implement a table feature?

Asked by 3 years ago
Edited 3 years ago

Hello! Recently, I’ve been having some troubles implementing a “BackTrack” feature that allows you to go back to a table’s parent. For example, say we define a table such as Table1 = { Table2 = {} }

The main question is: "If you ONLY had Table2, How would you get Table1?" So far, I’ve made a ModuleScript that will temporarily work. The reason it’s temporary is that I can’t turn a directory into a string. Doing so will return a hexadecimal code of the actual table that is in the directory. Here is the first iteration of my work:

local module = {}

function module.BackTrack(str, original)
    local split = str:split('.')
    print(split)
    local last = split[#split]
    assert(#split-1 ~= 0, 'backtrack cant be used on single tables')
    local before = #split-1
    local current = original
    warn(before)
    for i = 2, before do
        current = current[split[i]]
    end
    return current
end

return module

Thank you for looking at my post, And I hope you can help me, reader!

1 answer

Log in to vote
0
Answered by
Speedmask 661 Moderation Voter
3 years ago
Edited 3 years ago

well, look who it is. I just answered your last question but here is a small "ordered table" object you can use to replace any standard table. it just makes any inserted table keep a record of its parent in itself and become another OrderedTable. let me know if you have any questions about how it works.

local OrderedTable = {}
OrderedTable.__index = OrderedTable
OrderedTable.__newindex = function(taaable, index, value)
    rawset(taaable, index, type(value) == "table" and OrderedTable.new(value, taaable) or value)
end

function OrderedTable.new(taaable, parent)
    taaable = taaable or {}
    taaable.Parent = parent
    return setmetatable(taaable, OrderedTable)
end

function OrderedTable:Climb(ancestors)
    local ancestor = self
    for _ = 1, ancestors do
        ancestor = ancestor.Parent
    end
    return ancestor
end

local test = OrderedTable.new()
test.cool = {}
test.cool.dope = {}
test.cool.dope.wow = {}

print(test)
print(test.cool.dope.Parent)
print(test.cool.dope.wow:Climb(3))
Ad

Answer this question