4

I have a nested table like so:

  t1 ={}
  t1[1] = {col1=1,col2=1,col3=1,col4=1}
  t1[2] = {col1=1,col2=1,col3=1,col4=1}
  t1[3] = {col1=1,col2=1,col3=1,col4=1}
  t1[4] = {col1=1,col2=1,col3=1,col4=1}

it's actually much larger with 250 items in t1 and 30 items per nested table so what I want to do is loop through and get sub table values like this:

 for i = 2, 4 do
  local width = t1[draw.ID].col1 --draw.ID is got elsewhere
 end

but changing the number part of .col1 to the i part so when it loops through it gets:

 t1[draw.ID].col2
 t1[draw.ID].col3
 t1[draw.ID].col4

I'm using Lua 5.1.

2 Answers 2

6
for i= 2, 4 do
  local width = t1[draw.ID]["col" .. i] --draw.ID is got elsewhere
end
Sign up to request clarification or add additional context in comments.

Comments

3

Ideally, col would be or would contain an array-like table or sequence. This is a much more scalable way to accomplish what you're trying to do. String concatenation ['col' .. i] to access table keys in the fashion that you'd access them as an array is costly and unnecessary, if it can be avoided. This is especially important if this is something you plan to do often and want to work quickly.

-- Elements of t1 contain tables with cols.
local t1 = {}
t1[1] = {cols = {1,1,1,1}}
t1[2] = {cols = {1,1,1,1}}
t1[3] = {cols = {1,1,1,1}}
t1[4] = {cols = {1,1,1,1}}

for i=2, 4 do
  local width = t1[draw.ID].cols[i]
end

-- Elements of t1 are the cols.
local t1 = {}
t1[1] = {1,1,1,1}
t1[2] = {1,1,1,1}
t1[3] = {1,1,1,1}
t1[4] = {1,1,1,1}

for i=2, 4 do
  local width = t1[draw.ID][i]
end

Edit: If it's unavoidable that you have to use table keys in the style of ['col' .. i], then the best you could do is to cache them for faster access.

-- Cache all the possible keys that you'll need.
local colkeys = {}
for i=1, 30 do colkeys[i] = 'col' .. i end

for i=2, 4 do
  local width = t1[draw.ID][colkeys[i]]
end

This method is anywhere from 4 to 8 times faster than concatenating a string each time that you need to index the table. It's not the ideal solution, but it works if you're stuck with the likes of col1 to col30.

1 Comment

Thanks Ryan, ended up changing the whole code so the elements of t1 contain tables with cols.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.