Convert Lua Table

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

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

Does lua have a built-in method for this?

+7
lua-table lua
source share
2 answers

In your recent comment, try the following:

 local bar, iMax = {}, #foo for i = 1, iMax, 2 do bar[foo[i]] = foo[i + 1] end 
+6
source share

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 as follows:

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

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

+4
source share

All Articles