How do I rename a key in an array?

Since it is not possible to rename a key value in an array using LiveCode, this lesson will demonstrate deleting an existing key in an array and placing the value in a new key.

Manipulating Arrays

Putting elements into an array and getting their values uses the self explanatory "put...into..." syntax:

put "value" into tArray["key"]
put tArray["key"] into tElementValue

If the array doesn't have an element with a particular key then the element value will be empty.

Obtaining the Keys of an Array

The keys function returns a list of the elements of the array. For example:

function GetExampleArrayKeys
   
	local tArray
   
	put "a" into tArray["1"]
	put "b" into tArray["2"]
	put "c" into tArray["d"]
	return (the keys of tArray)
   
end GetExampleArrayKeys

Would return the value:

1

2

d

It should be noted that the keys of an array will not be returned in any alphabetical, numeric or chronological order.

Deleting an Element From an Array

To delete an element from an array we simply use the delete variable command as demonstrated below:

function GetExampleArrayKeys
   
	local tArray
   
	put "a" into tArray["1"]
	put "b" into tArray["2"]
	put "c" into tArray["d"]
	delete variable tArray["2"]
   
	return (the keys of tArray)
   
end GetExampleArrayKeys

Would return the value:

1

d

Putting it all together...

Now we can create and delete elements of the array it becomes simple to write a function that takes the array, the current key name and the replacement key name as parameters and returns the array with the value moved to the replacement key.

function RenameKeyArray pArray, pCurrentKey, pNewKey
	local tElementValue
   
	put pArray[pCurrentKey] into tElementValue
   
	delete variable pArray[pCurrentKey]
   
	put tElementValue into pArray[pNewKey]
	return pArray
   
end RenameKeyArray

0 Comments

Add your comment

E-Mail me when someone replies to this comment