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 ?
From your recent comment, try this:
local bar, iMax = {}, #foo
for i = 1, iMax, 2 do
bar[foo[i]] = foo[i + 1]
end
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With