lua-users home
lua-l archive

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




On Monday, December 2, 2013, Philipp Janda wrote:
Am 03.12.2013 02:48 schröbte Andrew Starks:
I get the upvalue. It's on the stack. It's value is 0. I want it so that
the next time I enter the c function and retrieve the value at the same
lua_upvalueindex address, it returns unto me the previous value, added
to one.

Please to illustrate?

    static int iter( lua_State* L ) {
      /* increment and push value to stack */
      lua_pushinteger( L, lua_tointeger( L, lua_upvalueindex( 1 ) )+1 );
      /* replace upvalue with incremented value at stack top */
      lua_replace( L, lua_upvalueindex( 1 ) );
      /* lua_replace popped the updated value, so push it again to
       * return it */
      lua_pushvalue( L, lua_upvalueindex( 1 ) );
      return 1;
    }

On the Lua side:

    > print( iter() )
    1
    > print( iter() )
    2
    > print( iter() )
    3

I hope that's what you wanted ...


-Andrew


Philipp



Holy crap! Thank you! I didn't mean to be so obstinate. However , I read the definition of lua_replace over and over again as part of my search. Then when it was brought up, I went to check on it again and was relieved  (sad, too) that it was described like remembered, such that the following would be equivalent to it:

lua_insert(L, -2);
lua_remove(L, -1);

That is, remove the reference to the value at the index and insert the top value in its place so that everything else stays put.  Here is the cut and paste:

lua_replace

[-1, +0, –]

void lua_replace (lua_State *L, int index);

Moves the top element into the given valid index without shifting any element (therefore replacing the value at the given index), and then pops the top element.


Am I the only one that reads that incorrectly?