lua
[Ported from github.com/lua/lua] Cast in 'rl_readline_name'
Brought by drakestapleton
| 1 | /* implementation for lib2-v2 */ |
| 2 | |
| 3 | #include <string.h> |
| 4 | |
| 5 | #include "lua.h" |
| 6 | #include "lauxlib.h" |
| 7 | |
| 8 | static int id (lua_State *L) { |
| 9 | lua_pushboolean(L, 1); |
| 10 | lua_insert(L, 1); |
| 11 | return lua_gettop(L); |
| 12 | } |
| 13 | |
| 14 | |
| 15 | struct STR { |
| 16 | void *ud; |
| 17 | lua_Alloc allocf; |
| 18 | }; |
| 19 | |
| 20 | |
| 21 | static void *t_freestr (void *ud, void *ptr, size_t osize, size_t nsize) { |
| 22 | struct STR *blk = (struct STR*)ptr - 1; |
| 23 | blk->allocf(blk->ud, blk, sizeof(struct STR) + osize, 0); |
| 24 | return NULL; |
| 25 | } |
| 26 | |
| 27 | |
| 28 | static int newstr (lua_State *L) { |
| 29 | size_t len; |
| 30 | const char *str = luaL_checklstring(L, 1, &len); |
| 31 | void *ud; |
| 32 | lua_Alloc allocf = lua_getallocf(L, &ud); |
| 33 | struct STR *blk = (struct STR*)allocf(ud, NULL, 0, |
| 34 | len + 1 + sizeof(struct STR)); |
| 35 | if (blk == NULL) { /* allocation error? */ |
| 36 | lua_pushliteral(L, "not enough memory"); |
| 37 | lua_error(L); /* raise a memory error */ |
| 38 | } |
| 39 | blk->ud = ud; blk->allocf = allocf; |
| 40 | memcpy(blk + 1, str, len + 1); |
| 41 | lua_pushexternalstring(L, (char *)(blk + 1), len, t_freestr, L); |
| 42 | return 1; |
| 43 | } |
| 44 | |
| 45 | |
| 46 | /* |
| 47 | ** Create an external string and keep it in the registry, so that it |
| 48 | ** will test that the library code is still available (to deallocate |
| 49 | ** this string) when closing the state. |
| 50 | */ |
| 51 | static void initstr (lua_State *L) { |
| 52 | lua_pushcfunction(L, newstr); |
| 53 | lua_pushstring(L, |
| 54 | "012345678901234567890123456789012345678901234567890123456789"); |
| 55 | lua_call(L, 1, 1); /* call newstr("0123...") */ |
| 56 | luaL_ref(L, LUA_REGISTRYINDEX); /* keep string in the registry */ |
| 57 | } |
| 58 | |
| 59 | |
| 60 | static const struct luaL_Reg funcs[] = { |
| 61 | {"id", id}, |
| 62 | {"newstr", newstr}, |
| 63 | {NULL, NULL} |
| 64 | }; |
| 65 | |
| 66 | |
| 67 | LUAMOD_API int luaopen_lib2 (lua_State *L) { |
| 68 | lua_settop(L, 2); |
| 69 | lua_setglobal(L, "y"); /* y gets 2nd parameter */ |
| 70 | lua_setglobal(L, "x"); /* x gets 1st parameter */ |
| 71 | initstr(L); |
| 72 | luaL_newlib(L, funcs); |
| 73 | return 1; |
| 74 | } |
| 75 | |
| 76 |