lua-users home
lua-l archive

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


Gang,

Is the stack top on entry to a C routine I've registered **guaranteed** to
always indicate the number of parameters passed?

Or another way of asking: is the stack top prior to lua pushing any
arguments **guaranteed** to always be at zero?

I'm looking to use a single C routine as a dispatcher that takes a different
number of arguments:

>From Lua, eg:

Dispatch(100, self, x, y);   -- 100 means SetLocation
Dispatch(101, self, "foo");  -- 101 means SetName

So, is it guaranteed that in my C routine the dispatch number (100, 101,
etc) will always be at index 1?  And the self parameter at 2?

So will it be safe to do this:

int Dispatch(lua_State *L)
{
    double  x, y;
    void    *selfPtr;
    char    *name;

    selfPtr = lua_touserdata(L, 2);    -- "self" always at absolute index 2?

    switch ((int)lua_tonumber(L, 1))   -- "number" always at index 1?
        {
        case 100:
            x = lua_tonumber(L, 3);
            y = lua_tonumber(L, 4);
           
            ...

            break;

        case 101:
            name = lua_tostring(L, 3);

            ...

            break; 
        }

    return 0;
}

The docs say "A C function receives its arguments from Lua in its stack...".

Surely, if I always clean my stack properly, the stack will start at zero
before Lua pushes the args to my C routine.  But what happens if I have a
bug and accidentally let my stack grow?

Will the first argument then be at index <prior stack top> + 1?

Thx,
Ando