lua-users home
lua-l archive

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


>> Yes that looks good. But I have a vector/matrix library written in C++ that
>> I want to use. I'd like to make it as easy as possible for my (LUA
>> implemented as script) users to access elements. Therefore I have an
>> overloaded operator ().

How about something like this

-- Function to create a '2D array' with methods
function arrayNew()
    local localTable = {}
    
-- this method sets the value in the array at Col, Pos to value
    localTable.setArrayValue = function (arrayA, Col, Pos, Value)
    local column = arrayA[Col]
    if type(column) == "nil" then arrayA[Col] = {}; column = arrayA[Col] end
    if type(column) == "table" then column[Pos] = Value return 1    end
    return nil
    end

-- this method gets the value in the array at Col, Pos
    localTable.arrayValue = function (arrayA, Col, Pos)    
        local column = arrayA[Col]
        if type(column) == "table" then  return column[Pos] end
        return nil
    end

-- clone makes a simple 'deep copy' of the table
    localTable.clone = function (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 
-- uses an upvalue to access the function clone in localTable
-- in the enclosing scope
            v = %localTable.clone(v)
        end
        newTable[i] = v
        i, v = next(aTable, i)
        end
        return newTable
    end
    
    return localTable
end

local theArray = arrayNew()
theArray:setArrayValue(1, 1, "1,1")
theArray:setArrayValue(1, 20, "1,20")
theArray:setArrayValue(20, 1, "20,1")
write("theArray(1,1) = ",theArray:arrayValue(1,1),"\n")
write("theArray(20,1) = ",theArray:arrayValue(20,1),"\n")
newArray = theArray:clone()
write("newArray(20,1) = ",newArray:arrayValue(20,1),"\n")
newArray:setArrayValue(20,1,"changed 20,1")
write("theArray(20,1) = ",theArray:arrayValue(20,1),"\n")
write("newArray(20,1) = ",newArray:arrayValue(20,1),"\n")

otherwise you will have to make the array or matrix a 'userdata'

Paul.

Paul.