lua-users home
lua-l archive

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


Christoph Schreiber wrote:
> I am trying to expose my C/C++ matrix-library to lua and I'd really like my
> users to be able to access the data using a C-like 2-dimensional array
> notation, e.g. mymatrix[2][3] = 65. The code below works well but as you can
> see (make_rowptr) it creates a lua-user-data-object at every row access. Is
> this the most efficient way to get the "[][]" notation? Any ideas?

Yes. You can use the userdatum environment to cache the rows:
 
// Warning: untested!
int get(lua_State* L) // exported method
{
    type* self = static_cast<T>(luaL_checkudata(L, index, TYPEID);
    lua_Integer i = luaL_checkinteger(L, 2);
    luaL_argcheck(L, 1 <= i && i <= self->m_rows, 2, "index out of range");
    lua_getfenv(L, index); // get matrix env
    lua_rawgeti(L, -1, i);
    if (lua_isnil(L, -1)) { // not cached?
        lua_pop(L, 1);
        make_rowptr(L, self->m_data[i - 1], self->m_cols);
        lua_pushvalue(L, -1);
        lua_rawseti(L, -3, i); // cache row
    }
    return 1;
}

void make_rowptr(lua_State* L, lua_Number* data, lua_Integer size)
{
    vector::type* self= static_cast<vector::type*>(
        lua_newuserdata(L, sizeof(vector::type)));
    self->m_delete = false;
    self->m_size = size;
    self->m_data = data;
    luaL_getmetatable(L, vector::TYPEID);
    lua_setmetatable(L, -2);
    lua_newtable(L);
    lua_setfenv(L, -2);
}


Cheers,
Luis

-- 
Computers are useless. They can only give you answers.
                -- Pablo Picasso

-- 
Luis Carvalho (Kozure)
lua -e 'print((("lexcarvalho@NO.gmail.SPAM.com"):gsub("(%u+%.)","")))'