5

I am having a table in which I am passing names:

names = {'Sachin', 'Ponting', 'Dhoni'}

and in other table I am passing country names:

country = {"India", "Australia", "India"}

I want output table like:

out_table = {Sachin="India", Ponting="Australia", Dhoni="India"}

Kamiccolo
  • 7,758
  • 3
  • 34
  • 47
Prashant Gaur
  • 9,540
  • 10
  • 49
  • 71

2 Answers2

2

You can make a new iterator that get values from both sequences:

function both_values(t1, t2)
    local i = 0
    return function() i = i + 1; return t1[i], t2[i] end
end

Then use the iterator like this:

local out_table = {}
for v1, v2 in both_values(names, country) do
    out_table[v1] = v2
end
Yu Hao
  • 119,891
  • 44
  • 235
  • 294
  • It is giving error . stdin:2: attempt to index global `out_table' (a nil value) – Prashant Gaur Nov 14 '13 at 06:24
  • @PrashantGaur Are you testing the program in the Lua interpreter line by line? If so, declare `out_table` as global, i.e, `out_table = {}` without `local`. – Yu Hao Nov 14 '13 at 06:34
  • why this ? can you explain i am new to lua – Prashant Gaur Nov 14 '13 at 06:41
  • 3
    @PrashantGaur Because in interactive mode, each line is a chunk by itself (unless it is incomplete). When you entered the next line, the previous local declaration is out of scope. – Yu Hao Nov 14 '13 at 06:49
2

Here's a straight-forward attempt:

names = {'Sachin', 'Ponting', 'Dhoni'}
countries = {"India", "Australia", "India"}

function table_map(names, countries)
    local out = {}
    for i, each in ipairs(names) do
        out[each] = countries[i]
    end
    return out
end

out_table = table_map(names, countries)

Live repl demo.

greatwolf
  • 20,287
  • 13
  • 71
  • 105