lua-users home
lua-l archive

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]


From: "Chris" <chris@wulfenia.com>
> How can I implement a USER-friendly method to work with 2-dimensional
> arrays/matrices. (i.e. create, redim, access elements etc.)? 
> I'd like to allow my users to do something like...

Here's an example of doing it using lua tables as sparse arrays:

function arrayNew(NumCols, NumRows)
  return {}
end

function arrayValue(arrayA, Col, Pos)    
  local col = arrayA[Col]
  if type(col) == "table" then return col[Pos] end
  return nil
end

redim isn't needed.

> arrayC = arrayA     -- copy whole array

How about: arrayC = clone(arrayA)

function clone(aTable)
  if type(aTable) ~= "table" then 
    return aTable 
  end
  local newTable = {}
  local i, v = next(aTable, nil)
  while i ~= nil do
    if type(v) == "table" then v = clone(aTable)
    newTable[i] = v
    i, v = next(aTable, i)
  end
  return newTable
end

> arrayD = arrayA+arrayB   --arithmetic operators

How about: arrayD = arrayAdd(clone(arrayA), arrayB)

function arrayAdd(arrayA, arrayB)
  if type(arrayA) ~= "table" or type(arrayB) ~= "table" then
    error("arrayAdd("..type(arrayA)..", "..type(arrayB)..") - both arguments must be tables")
  end

  local i, bValue= next(arrayB, nil)
  while i ~= nil do
    local aValue = arrayA[i]
    if aValue then 
      if type(aValue) == "table" then 
          arrayAdd(aValue, bValue)
      else
        arrayA[i] = aValue + bValue
      end
    else 
        arrayA[i] = clone(bValue)
    end
    i, bValue = next(arrayA, i)
  end
  return arrayA
end

Note: This code isn't tested - I just wrote it in this email.

Steve