Terry English
Terry English

Reputation: 23

Lua search through table

I am working on a game project using Corona SDK and I am running into an issue. I am trying to use string.find() in a for loop to test to determine if a value is in a certain table and if so, add that value to another table. My problem is that since string.find()/string.match does not read duplicates in this case (assuming that the for loop is the reason why). I am essentially only having "1102", "1103" instead of "1102", "1102", "1103", "1102", in the "copy" table which is how I am trying to get this to do. Any suggestions?

database = 
{
 {name="test", serial="1102", img="src/1.png"},
 {name="test2", serial="1103", img="src/2.png"},
 {name="test3", serial="1104", img="src/3.png"}
}

list = 
{
 "1102",
 "1102",
 "1103",
 "1102"
}

copy = {}
n=1

for i=1, #database do
 if string.find(database[i].serial, tostring(list[n])) then 
   table.insert(copy, database[i].img)
   n=n+1
 end
end    
for i=1, #copy do 
    print(copy[i])
end

Upvotes: 2

Views: 538

Answers (2)

lyravega
lyravega

Reputation: 101

Are the serials in the database table unique? If so, From the code, I think you can make your database table to be more efficient.

local database = 
{
 [1102] = {name="test", img="src/1.png"},
 [1103] = {name="test2", img="src/2.png"},
 [1104] = {name="test3", img="src/3.png"}
}

Note that, with this change, you cannot use iterative for loops to navigate in the database table. However, the part where you do the check becomes this:

local list = {1102,1102,1103,1102,}
local copy = {};
for index, serial in next, list do 
    if database[serial] then copy[#copy+1] = database[serial].img end
end

For the last part, you can use table.concat() to print values of a table as a string, instead of iterating over it one by one:

table.concat(copy, "\n")

And lastly, I know the code you've written up there is an example, but be careful about global variables; I hope they (database, list, copy) are not global in your code. Anyway,

With Regards, lyr

Upvotes: 0

Yu Hao
Yu Hao

Reputation: 122383

Using a nested loop works.

for lk, lv in ipairs(list) do
  for dk, dv in ipairs(database) do
    if string.find(dv.serial, tostring(lv)) then 
      table.insert(copy, dv.img)
    end
  end
end

I'm using ipairs, which is similar to for i=1, #list do.

Upvotes: 1

Related Questions