Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Lua table convert

Tags:

lua

lua-table

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 ?

like image 367
Yohn Avatar asked Nov 12 '13 07:11

Yohn


2 Answers

From your recent comment, try this:

local bar, iMax = {}, #foo
for i = 1, iMax, 2 do
    bar[foo[i]] = foo[i + 1]
end
like image 134
hjpotter92 Avatar answered Nov 07 '22 19:11

hjpotter92


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.

like image 38
Yu Hao Avatar answered Nov 07 '22 19:11

Yu Hao