[Date Prev][Date Next][Thread Prev][Thread Next]
[Date Index]
[Thread Index]
- Subject: Re: [proposal] limit(n, ...)
- From: Daniel Silverstone <dsilvers@...>
- Date: Fri, 11 Oct 2019 08:48:29 +0100
On Thu, Oct 10, 2019 at 08:54:08 -0300, Soni L. wrote:
> it'd be nice to have a limit() function companion to select() where select
> skips the first n and limit skips everything after n.
>
> e.g. limit(1) --> nothing, limit(1, 1, 2, 3) --> 1, etc
In most languages this would be called "take" and it is indeed a useful
thing to be able to do.
I'd guess an implementation might look like:
```c
static int
lua_take(lua_State *L)
{
lua_Integer n_items = MIN(luaL_checkinteger(L, 1), lua_gettop(L, -1) - 1);
lua_remove(L, 1);
lua_settop(L, n_items);
return n_items;
}
```
It has been a while since I wrote Lua/C code though, so who knows how badly
wrong that is :D
For your first example, the stack is [1] on input, so n_items is set to MIN(1,
1 - 1) which will be 0. We remove the 1, set top to 0 and return 0 items,
matching your limit(1) --> nothing.
For your second example, the stack is [1 1 2 3] on input, so n_items is set to
MIN(1, 4 - 1) which will be 1. Remove the 1, truncate to 1 items, return it.
Works again.
D.
--
Daniel Silverstone http://www.digital-scurf.org/
PGP mail accepted and encouraged. Key Id: 3CCE BABE 206C 3B69