So I have some tables here:
local table1 = {
{1, 3, 5, 7},
{2, 4, 6, 8}
}
How can I print number “8” in that table?
SOLUTION:
print(table1[#table1][#table1[#table1]])
So I have some tables here:
local table1 = {
{1, 3, 5, 7},
{2, 4, 6, 8}
}
How can I print number “8” in that table?
SOLUTION:
print(table1[#table1][#table1[#table1]])
Do you mean you want to index the tables as though they were the top-level table?
like:
print(table1[8])
??
Yep, that’s what I want to do!
If you wanted to find 8 specifically I believe table.find(table1, 8) would work.
If you wanted to index the particular position (untested): table1[2][4]
A multidimensional table is just a table as an element of another table.
So table1[2]
would be:
{2, 4, 6, 8}
And so table1[2][4]
would be 8.
If you wanted to search for a value in a 2d table you would have to use a nested loop:
for a, subtable in ipairs(table1) do
for b, value in ipairs(subtable) do
if (value == 8) then
print("value is at " .. a .. ", " .. b)
return
end end
Alright then you can achieve this with a simple 2D array search function:
local Table1 = {
{1,2,3,4},
{5,6,7,8}
}
local function Find2D(t, i)
for Index,Value in ipairs(t) do
if typeof(Value) == "table" then
for Key, V in ipairs(Value) do
if Index*Key == i then
return V
end
end
end
end
end
print(Find2D(Table1, 8))
This would also work if you had arbitrary values in those indices, so long as they’re inserted with table.insert() so as to avoid it becoming a dictionary.
Edit:
Another example to show what I meant by arbitrary values:
local Table1 = {
{1,2,3,4},
{5,6,7,"Hello, World!"}
}
local function Find2D(t, i)
for Index,Value in ipairs(t) do
if typeof(Value) == "table" then
for Key, V in ipairs(Value) do
if Index*Key == i then
return V
end
end
end
end
end
print(Find2D(Table1, 8))
But what if I have each sub-tables has a lot of numbers in there. For example:
local table1 = {
{--[[There are lots of numbers in here--]]}
}
How can I index the number in a subtable (subtable = #table1
) which is number = #subtable
Oh! I found a solution! Thanks for your help guys!
Why are you doing Index * Key
? Your search function does not locate the requested target itself.
If I understood your question right,
local function FindNumberMatchingSubtableLength(Tables)
for Index, Subtable in ipairs(Tables) do
local Number = table.find(Subtable, #Subtable)
if Number then
return Index, Number
end
end
end
If you’re concerned about runtime, consider applying a Binary Search
That’s on me, I’m honestly too tired to think about multi-dimensional arrays at all…
Either way, cheers, have a good day/night/afternoon.
local number8 = table1[2][4]