lua-users home
lua-l archive

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


Here is simple example from my app. Note that this is not copy/paste
(my companie's policy forbids it) so in may contain typos. This code
is addition to my last message, which contained function exported to
Lua that returned userdata to Lua script.

This function receives userdata from Lua script, casts it back to C++
object and performs some operation on it:

int LuaCanvas::line_set(lua_State *lua)
{
    luaL_checktype(lua,1,LUA_TLIGHTUSERDATA);
    QCanvasLine *line = static_cast<QCanvasLine*>(lua_touserdata(lua,1));
    double x1 = luaL_checknumber(lua,2);
    double y1 = luaL_checknumber(lua,3);
    double x2 = luaL_checknumber(lua,4);
    double y2 = luaL_checknumber(lua,5);

    line->setPoints(x1,y1,x2,y2);
    return 0;
}

and this is how is looks like from Lua script's point of view:

--creating new line and assigning it to "myLine" variable (will
contain "userdata" type)
myLine = line_new()
--passing it to other api func listed above
line_set(myLine,100,100,200,200)

Very simple :)

Hope it helps you. 

On Apr 1, 2005 3:26 AM, Nguyen Dang Quang <quangnd412@yahoo.ca> wrote:
> Hi Pavel Antokolsky,
> 
>     Thank for replying me. Could you send me a sample code in with you pass
> an pointer to LUA and LUA store it in a variable and then LUA pass back this
> pointer to other C pointer. Thank you very much.
> 
> ----- Original Message -----
> From: "Pavel Antokolsky aka Zigmar" <zigmar@gmail.com>
> To: "Lua list" <lua@bazar2.conectiva.com.br>
> Sent: Thursday, March 31, 2005 7:00 PM
> Subject: Re: Pass pointer into LUA
> 
> > There is no need to use numerical type to store pointer, and sure it
> > unsafe. There is a special datatype for passing pointers into lua:
> > "light userdata".
> > For more documentation see "lua_pushlightuserdata" and  #28.5 in
> > "Programming in  Lua book".
> >
> > Here is a small code snipplet:
> > The function exported to Lua that creates C++ object and returns
> > userdata with pointer to it:
> >
> > int LuaCanvas::line_new (lua_state *lua)
> > {
> > QCanvasLine *line = new QCanvasLine(getCanvas(lua));
> > lua_pushlightuserdata(lua,line)
> > return 1;
> > }
> >
> > "getCanvas()" function retrivies the pointer to LuaCanvas object (the
> > exported method is static) stored in lua registry. If you are
> > interested, I can also send you a snippled how this pointer is stored
> > and retrivied.
> >
> >
> >
> > On Thu, 31 Mar 2005 16:35:15 +0700, Nguyen Dang Quang
> > <quangnd412@yahoo.ca> wrote:
> > > Hi,
> > > I have a big problem with passing pinter to LUA. In LUA documents, they
> say
> > > that programers can use LUA number (in fact a double type!) but it
> sounds
> > > not safe at all when storing pointer in a double number form! How can I
> > > solve this problem?
> > >
> > >
> >
> >
> > --
> > Best regards,
> > Zigmar
> 
> 


-- 
Best regards,
Zigmar