lua-users home
lua-l archive

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


On Mon, Aug 3, 2015 at 1:55 PM, Tim Hill <drtimhill@gmail.com> wrote:
> In the 5.3 reference for lua_checkstack(), the docs state:
>
> int lua_checkstack (lua_State *L, int n);
>
> "Ensures that the stack has space for at least n extra slots. It returns
> false if it cannot fulfill the request, either because it would cause the
> stack to be larger than a fixed maximum size (typically at least several
> thousand elements) or because it cannot allocate memory for the extra space.
> This function never shrinks the stack; if the stack is already larger than
> the new size, it is left unchanged.”
>
> I read this as meaning that the desired total stack size is "lua_gettop() +
> n”, that is, n is the incremental additional size (not an absolute stack
> size). In this case, how can the last sentence “if the stack is already
> larger than the new size” ever be true, unless the API allows negative
> values for n? Put another way, if the current stack size is S, then the API
> adjusts the stack size to S + n, then unless we allow negative n, (S + n >=
> S) will always be true?
>
> —Tim
>

After a pop operation, the capacity of the stack is larger than the
position of the top of the stack. That is to say, lua_gettop() does
not answer "what is the size of the stack?"

lua_checkstack() exists to ensure that there's enough memory reserved
for an upcoming series of push operations. If there is enough such
memory reserved, it doesn't need to do anything. If there isn't
enough, then it allocates more, unless this allocation would overflow
the constraints on the maximum stack size. If there's MORE than enough
memory reserved, lua_checkstack() does not reclaim it, but leaves it
allocated. (What if a higher stack frame had preallocated memory for
its own use that it hadn't used up yet before it called a function
that called lua_checkstack()?)

If there's an issue here, it's that the word "size" is somewhat
overloaded and one sense ought to be replaced with the word "capacity"
in the documentation to disambiguate it.

/s/ Adam