PDA

View Full Version : Associative table index using a variable?


Buffman
01-12-2007, 10:07 AM
Hi Everyone,

I'm sure this has been addressed before, but I couldn't find it searching through the forums. How can I create a table index using a variable? Here's an example:

sIndex = "Anderson";
sValue = "Jason";

arrNames.sIndex = sValue; or arrNames = {sIndex=sValue}; will result in "arrNames.sIndex" rather than "arrNames.Anderson"

I thought I could get away with Table.Insert, but it only works for numeric arrays.

How can I dynamically create an associative array using variables?

azmanar
01-12-2007, 11:23 AM
Hi,

A few ways to define table arrays.

METHOD 1:


arrNames = {anderson="johnson"};

--therefore making it into a variable:

sName = arrNames.anderson;



resultant : sName = johnson


METHOD 2:


arrNames = {};
arrNames[1] = {anderson="johnson"};

--- therefore making it into a variable:

sName = arrNames[1];


resultant : sName = johnson

--------------- so if I choose METHOD 1----------------

--define variables

sIndex = "anderson";
sValue = "johnson";

arrNames = { sIndex = sValue }

-- making it into another variable

sName = arrNames.sIndex;

resultant : sName = johnson

Lorne
01-12-2007, 11:53 AM
You can also do

sIndex = "anderson";
sValue = "johnson";

arrNames[sIndex] = sValue;

Buffman
01-12-2007, 12:03 PM
Thanks Azmanar,

Here's the problem I'm running into though. Working off your examples (method1 in this case), when I do this:

for index, value in arrNames do
Dialog.Message("", "Index is: "..index);
Dialog.Message("", "Value is: "..value);
end

the value is fine, but I'll get "Index is: sIndex" instead of "Index is: Anderson". Does this make sense?

Buffman
01-12-2007, 12:06 PM
You can also do

sIndex = "anderson";
sValue = "johnson";

arrNames[sIndex] = sValue;

Ahhh Thanks Lorne, that worked. I thought []'s were for numeric arrays only, but it works for associative arrays too! Yay!

azmanar
01-12-2007, 12:17 PM
Sorry. I was wrong about METHOD 2.

METHOD 2:

Should be:

arrNames = {};
arrNames[1] = {"johnson"};
sName = arrNames[1];

RESULTANT : sName = johnson

and if I want to nest it further, it should be

Should be:

arrNames = {};
arrNames[1] = {anderson = "johnson"};
sName = arrNames[1].anderson;

RESULTANT : sName = johnson


Attached is an APZ for your reference.