Making Variables from a table

Posted by FenceWalker on Sun 17 Oct 2010 08:39 PM — 7 posts, 30,299 views.

USA #0
I have a table right now that goes something like this:

1 = "dogs=2"
2 = "cats=3"
3 = "dogs_and_cats=2 3"


Is there a way to somehow loop through this table and set anything in the value field, before the = sign to the name of a variable and anything after no matter what it is to the value?
Amended on Sun 17 Oct 2010 09:06 PM by FenceWalker
Netherlands #1
What you want is possible. However, I am not going to give you the answer. (Sorry, mean streak of mine.)

Instead, I will ask you - how are you getting this table with this particular listing? Is it a part of some persistence mechanism you are working on to save variables across sessions?

Template:post=4960
Please see the forum thread: http://gammon.com.au/forum/?id=4960.


If that is not the case, I'll see about providing some snippet that matches what you ask for - but I think in this case the real problem might be that you are trying to implement something that has already been implemented once and seen a fair share of use. :)
USA #2
The table is actually one large string I have broken down to table format. I don't care about the variables saving across sessions I just want them assigned for use when the script is running. I just can't quite figure out how to separate the values of the table into new key = value pairs.
Australia Forum Administrator #3
http://www.gammon.com.au/scripts/doc.php?lua=string.match

That would be one way.

Something like:


key, value = string.match (s, "(%a+)=(.+)")

USA #4
So far I've come up with this:

function makeVars (k, v)
		for key, value in  string.gmatch (v, "(.+)=(.+)") do
		newtable [key] = value
		end
	end 

Then i use:

newtable = {}
table.foreach (t,makeVars)

Where t is the original table. This gives me a new table called newtable with the k, v pairs separated correctly.

Thanks for the help.
USA #5
table.foreach is actually deprecated. You can exactly duplicate its functionality with this:
for k,v in pairs(t) do
  makeVars(k, v)
end

And when you're at that point, you may as well do this:
local newtable = {}
for k,v in pairs(t) do
  for key, value in string.gmatch(v, "(.+)=(.+)") do
    newtable[key] = value
  end
end


One final note: When your table has ascending numeric keys, as yours does in your first post, you might want to consider using ipairs() instead. (The old-style equivalent would be table.foreachi; note the 'i')
local newtable = {}
for k,v in ipairs(t) do
  for key, value in string.gmatch(v, "(.+)=(.+)") do
    newtable[key] = value
  end
end

ipairs() just goes over the table items in order (i.e. t[1], t[2], t[3], etc.), and excludes non-number keys.
USA #6
Thanks for letting me know about table.foreach being deprecated. I missed that in my reading some how. Also thanks for helping me clean up what I already had.