lua-users home
lua-l archive

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


You could always return a table whose metatable has an __index method
that calls the appropriate function to get the 2d cell value.  I guess
this would be a form of currying.  The difference compared to your
proposed approach is that no userdata is created.  Instead,  a Lua
table with a properly designed metatable is returned.  Of course the
returned table will have to store somewhere the row it represents.

wes

On Fri, Apr 30, 2010 at 3:01 PM, Christoph Schreiber <luky0711@yahoo.de> wrote:
> Hi everybody,
> 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?
>
>
> 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");
>    make_rowptr(L, self->m_data[i - 1], self->m_cols);
>    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);
> }
>
> Thanks a lot and cheers
> Chris
>
>
>
>