Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Lua Nested Table Getting Elements

Tags:

lua

lua-table

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.

like image 699
Col_Blimp Avatar asked Jan 11 '23 13:01

Col_Blimp


2 Answers

for i= 2, 4 do
  local width = t1[draw.ID]["col" .. i] --draw.ID is got elsewhere
end
like image 51
Tim Cooper Avatar answered Jan 18 '23 20:01

Tim Cooper


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.

like image 30
Ryan Stein Avatar answered Jan 18 '23 22:01

Ryan Stein