lua-users home
lua-l archive

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


> 
> On 17-May-06, at 10:50 AM, Roberto Ierusalimschy wrote:
> 
> >>Suppose I'd like to keep references to a bunch of lua_Objects that
> >>were passed to my C function by Lua. The reference manual (no pun
> >>intended) says that lua_ref() will obtain a reference to the
> >>lua_Object that's on top of the stack, but does this apply for the
> >>"getting arguments" situation? In other words, is this the right way
> >>to obtain references to passed arguments (for later use), or am I way
> >>off? In the likely event that I'm "way off" -- how is this done
> >>correctly?
> >>
> >>void my_Lua_callable_function()
> >>{
> >>  int ref_to_param_1 = lua_ref(1);
> >>  lua_pop();
> >>  int ref_to_param_2 = lua_ref(1);
> >>  lua_pop();
> >>
> >>  // etc ...
> >>}
> >>
> >
> >This way is fine. If you need to use these parameters in the same  
> >function
> >after building their references, then you may prefer to copy thm to  
> >the
> >stack top (with lua_pushobject) and then call lua_ref. But if all  
> >you want
> >is to build the references, your code is quite Ok. (Except that the
> >signature of your function should be int foo (lua_State *L), and you
> >should pass this 'L' when calling lua_ref...)
> 
> Well, I forgot to mention that I'm using Lua 3.1 (it's forced by my  
> target platform, can't upgrade). In this case, I think the prototype  
> for a Lua callable C function is "void fun(void)", right?

Right. But then you have to change other stuff too...

I am not sure how much I remember about Lua 3.1, but I think the
parameters were not in the stack when the function was called.
So, you should first put them on the stack and then create the reference.
Something like this:

  lua_pushobject(lua_getparam(1));  /* push first parameter */
  int ref_to_param_1 = lua_ref(1);  /* create reference to it */
  ...

-- Roberto