7

I am new to lua, I have a table foo and I want to convert it to bar like following:

foo:{key1,value2,key2,value2} ==> bar:{key1=value1,key2=value2}

Does lua have a built-in method to do that ?

hjpotter92
  • 78,589
  • 36
  • 144
  • 183
Yohn
  • 866
  • 8
  • 11

2 Answers2

6

From your recent comment, try this:

local bar, iMax = {}, #foo
for i = 1, iMax, 2 do
    bar[foo[i]] = foo[i + 1]
end
Community
  • 1
  • 1
hjpotter92
  • 78,589
  • 36
  • 144
  • 183
4

This is one solution using an iterator:

function two(t)
    local i = -1
    return function() i = i + 2; return t[i], t[i + 1] end
end

Then you can use the iterator like this:

local bar = {}
for k, v in two(foo) do
    bar[k] = v
end

Note that it should be bar = {[key1]=value1, [key2]=value2}. In your example, {key1=value1,key2=value2} is a syntax sugar for string keys.

Yu Hao
  • 119,891
  • 44
  • 235
  • 294