lua-users home
lua-l archive

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


On Thu, Mar 6, 2014 at 8:29 PM, Fabio Carneiro <vizouk@gmail.com> wrote:
> Hi, i don't understand Upvalues very well and i'm trying to create a
> function that returns a string and has 2 upvalues, could someone give me a
> example of function that when debugged shows nups (number of upvalues) equal
> 2?
>
>
>
> static int teststring (lua_State *L) {
> int n = lua_gettop(L);
> std::str = "test"
> static int val;
> const char *cstr = str.c_str();
> lua_pushstring(L, cstr);
> return 1;
> }
>
> Now when i debug that function i want it to have 2 upvalues so i should use
>
>  lua_pushcclosure(L, &anotherfunc, 1);   ? I didn't quite understood this

The line "lua_pushcclosure(L, &anotherfunc, 1)" will pop 1 value from
the top of the stack and associate it as an upvalue for the function
'anotherfunc' -- afterward the closure (which is seen as just a
function on the Lua side) is pushed on the stack.  What I don't
understand is your 'anotherfunc' doesn't do anything with upvalues?
gettop() will tell you how many arguments were passed to the function,
as these are pushed onto the stack before the function is called, but
upvalues are not part of that number (they reside elsewhere).

To create a closure you push the upvalues on the stack, you then call
pushcclosure() telling it how many upvalues the function has.  These
get popped, and a function/closure is pushed onto the stack as a
return value.  Within the function itself you would use
lua_getupvalue(L, function_index, upvalue_index).
http://www.lua.org/manual/5.2/manual.html#lua_getupvalue

If you want to know how many upvalues a function has, you should look
into the lua_Debug structure:
http://www.lua.org/manual/5.2/manual.html#lua_Debug
You fill that structure in with this function:
http://www.lua.org/manual/5.2/manual.html#lua_getinfo

A dumber/simpler way would be to loop an integer from 1 to 256 (you
can't have more than 256 upvalues on a function).  You call
lua_getupvalue(L, function_index, int_value) and stop when it returns
NULL (meaning there was no upvalue at that index).  Of course, if you
are pushing the function from C you probably already know how many
upvalues a function has... ~