This is pretty hard to explain. So lets say we have a table of indexes
local iTable = {"a", "b", "c"}
And we have a normal table
local table = {"a" = {"b" = {"c" = 0}}}
Can you somehow change the value of “c” like this using the index table?
In other words, can you somehow iterate over the table and index table and do this:
function playerModule.GetData(plr, indexTable)
local data = playerModule.GetDataTable(plr)
local result = data
for i, v in pairs(indexTable) do
result = result[v]
if result == nil then
error("No value exist for this index table:"..indexTable)
end
end
return result
end
But how can you do this when setting a value in a table?
Yeah, i know that. i didnt test the code in studio. What i really mean is instead of doing this:
table["a"]["b"]["c"] = 1
How do i make a function that takes in a table, a index table, and the value to set that to?
(It’d do the same as the code above but it would be more flexible)
Something like this (ignore bad variable naming, I wrote this in a rush)
local itable = {"a", "b", "c"}
local function TableFunction(Table, pos)
local newTable = {}
if pos < #Table then
newTable[Table[pos]] = TableFunction(Table, pos + 1)
else
newTable[Table[pos]] = 0 -- set to whatever value
end
return newTable
end
print(TableFunction(itable, 1))
local function setTableFromIndices(t, is, v) --table, table of indices, value.
for i = 1, #is - 1 do
t = t[is[i]]
end
t[is[#is]] = v
end
local t = {a = {b = {c = 0}}}
setTableFromIndices(t, {"a", "b", "c"}, math.pi)
print(t.a.b.c) --3.14...
also here is a module for handling 2D arrays that might help
local module = {}
module.__index = module
module.New = function()
local self = setmetatable({}, module)
self.values = {}
return self
end
module.Get = function(self, a, b)
if self.values[a] == nil then return nil end
return self.values[a][b]
end
module.Set = function(self, a, b, value)
if value == nil then
if self.values[a] == nil then return end
self.values[a][b] = nil
if next(self.values[a]) ~= nil then return end
self.values[a] = nil
else
if self.values[a] == nil then self.values[a] = {} end
self.values[a][b] = value
end
end
return module
and can be used like this
local table2D = module.New()
table2D:Set("A", "B", 1)
print(table2D:Get("A", "B"))
local function setTableFromIndices(t, is, v) --table, table of indices, value.
for i = 1, #is - 1 do
if not t[is[i]] then t[is[i]] = {} end
t = t[is[i]]
end
t[is[#is]] = v
end
local t = {a = {b = {c = 0}}}
setTableFromIndices(t, {"l", "o", "l"}, math.pi)
print(t.l.o.l) --3.14...
I didn’t realize you wanted to support non-existent indices too.