Sunday, September 20, 2015

Working with Arrays

Pre-Conditions

This tutorial is written for LiveCode 6.6.2 stable and may not work with other releases. This document will not be updated.

Working with Arrays

Create a one dimensional array

put empty into myArray
put 1 into myArray["id"]
put "Herbert" into myArray["name"]

Create a two dimensional array

put empty into myArray
put 1 into myArray[1]["id"]
put "Herbert" into myArray[1]["name"]

put 2 into myArray[2]["id"]
put "James" into myArray[2]["name"]

Find the number of elements in an Array

put the number of lines of (the keys of myArray)

Push a value on to the end of an Array

put "value1" into myArray[the last line of the keys of myArray + 1]
put "value2" into myArray[the last line of the keys of myArray + 1]
put "value3" into myArray[the last line of the keys of myArray + 1]

Delete an element from an Array

delete variable myArray["myKey"]

Delete the value/contents of an array

put empty into myArray["myKey"]

Sort the keys of an array

put the keys of myArray into myKeys
sort lines of myKeys
repeat for each line myKey in myKeys
  -- do something with myArray[myKey]
end repeat

Shuffle the keys of an array

put the keys of myArray into myList
repeat number of lines of myList
  put random(number of lines of myList) into myKeyNr
  put line myKeyNr of myList & cr after myNewList
  delete line myKeyNr of myList
end repeat

Loop through an array by key

repeat  for each key tKey in myArray
  put "Key: " & tKey & ", Value: " & myArray[tKey]
end repeat

Loop through an array by value

repeat for each element tElem in myArray
  put tElem
end repeat

Debug the output of an Array

function displayArrayData pArray, pIndent
  -- create the variable that loops through the keys in the array
  local tKey
  if pArray is an array then
    -- print information to indicate that we are entering a new nested level of the array
    get "Array" & return
    -- print full stops that allow the reader to track the depth of an element
    put "." after pIndent
    -- create the indentation
    put tab after pIndent
    repeat for each key tKey in pArray
      -- call displayArrayData with a nested array
      put format("%s[%s] => %s\n", pIndent, tKey, displayArrayData (pArray[tKey], pIndent)) after it
    end repeat
    delete the last char of it
    return it
  else
    return pArray
  end if
end displayArrayData

Look at the official LiveCode Documentation for more details about this function.

No comments:

Post a Comment