Source:NetHack 5.0.0/src/nhlua.c

From NetHackWiki
Jump to navigation Jump to search

Below is the full text to nhlua.c from the source code of NetHack 5.0.0. To link to a particular line, write [[Source:NetHack 5.0.0/src/nhlua.c#line12]], for example.

The NetHack General Public License applies to screenshots, source code and other content from NetHack.

This content was modified from the original NetHack source code distribution (by splitting up NetHack content between wiki pages, and possibly further editing). See the page history for a list of who changed it, and on what dates.

1. /* NetHack 5.0	nhlua.c	$NHDT-Date: 1744963460 2025/04/18 00:04:20 $  $NHDT-Branch: NetHack-3.7 $:$NHDT-Revision: 1.153 $ */
2. /*      Copyright (c) 2018 by Pasi Kallinen */
3. /* NetHack may be freely redistributed.  See license for details. */
4. 
5. #include "hack.h"
6. #include "dlb.h"
7. 
8. #ifndef LUA_VERSION_RELEASE_NUM
9. #ifdef NHL_SANDBOX
10. #undef NHL_SANDBOX
11. #endif
12. #endif
13. 
14. #ifdef NHL_SANDBOX
15. #include <setjmp.h>
16. #endif
17. 
18. /*
19. #- include <lua5.3/lua.h>
20. #- include <lua5.3/lualib.h>
21. #- include <lua5.3/lauxlib.h>
22. */
23. 
24. /*  */
25. 
26. struct e;
27. 
28. #ifndef SFCTOOL
29. /* lua_CFunction prototypes */
30. #ifdef DUMPLOG
31. staticfn int nhl_dump_fmtstr(lua_State *);
32. #endif /* DUMPLOG */
33. staticfn int nhl_dnum_name(lua_State *);
34. staticfn int nhl_int_to_pm_name(lua_State *);
35. staticfn int nhl_int_to_obj_name(lua_State *);
36. staticfn int nhl_stairways(lua_State *);
37. staticfn int nhl_pushkey(lua_State *);
38. staticfn int nhl_doturn(lua_State *);
39. staticfn int nhl_debug_flags(lua_State *);
40. staticfn int nhl_flip_level(lua_State *);
41. staticfn int nhl_timer_has_at(lua_State *);
42. staticfn int nhl_timer_peek_at(lua_State *);
43. staticfn int nhl_timer_stop_at(lua_State *);
44. staticfn int nhl_timer_start_at(lua_State *);
45. staticfn int nhl_get_cmd_key(lua_State *);
46. staticfn int nhl_callback(lua_State *);
47. staticfn int nhl_gamestate(lua_State *);
48. staticfn int nhl_test(lua_State *);
49. staticfn int nhl_getmap(lua_State *);
50. staticfn char splev_typ2chr(schar);
51. staticfn int nhl_gettrap(lua_State *);
52. staticfn int nhl_deltrap(lua_State *);
53. #if 0
54. staticfn int nhl_setmap(lua_State *);
55. #endif
56. staticfn int nhl_impossible(lua_State *);
57. staticfn int nhl_pline(lua_State *);
58. staticfn int nhl_verbalize(lua_State *);
59. staticfn int nhl_parse_config(lua_State *);
60. staticfn int nhl_menu(lua_State *);
61. staticfn int nhl_text(lua_State *);
62. staticfn int nhl_getlin(lua_State *);
63. staticfn int nhl_makeplural(lua_State *);
64. staticfn int nhl_makesingular(lua_State *);
65. staticfn int nhl_s_suffix(lua_State *);
66. staticfn int nhl_ing_suffix(lua_State *);
67. staticfn int nhl_an(lua_State *);
68. staticfn int nhl_rn2(lua_State *);
69. staticfn int nhl_random(lua_State *);
70. staticfn int nhl_level_difficulty(lua_State *);
71. staticfn int nhl_is_genocided(lua_State *);
72. staticfn int nhl_get_debug_themerm_name(lua_State *);
73. staticfn void init_nhc_data(lua_State *);
74. staticfn int nhl_push_anything(lua_State *, int, void *);
75. staticfn int nhl_meta_u_index(lua_State *);
76. staticfn int nhl_meta_u_newindex(lua_State *);
77. staticfn int nhl_u_clear_inventory(lua_State *);
78. staticfn int nhl_u_giveobj(lua_State *);
79. staticfn void init_u_data(lua_State *);
80. #ifdef notyet
81. staticfn int nhl_set_package_path(lua_State *, const char *);
82. #endif
83. staticfn int traceback_handler(lua_State *);
84. staticfn uint32_t nhl_getmeminuse(lua_State *);
85. #ifdef NHL_SANDBOX
86. staticfn void nhlL_openlibs(lua_State *, uint32_t);
87. #endif
88. staticfn void *nhl_alloc(void *, void *, size_t, size_t);
89. staticfn lua_State *nhlL_newstate (nhl_sandbox_info *, const char *);
90. staticfn void end_luapat(void);
91. staticfn int nhl_get_config(lua_State *);
92. staticfn int nhl_variable(lua_State *);
93. staticfn void nhl_clearfromtable(lua_State *, int, int, struct e *);
94. staticfn void nhl_warn(void *, const char *, int);
95. staticfn void nhl_clearfromtable(lua_State *, int, int, struct e *);
96. staticfn int nhl_panic(lua_State *);
97. staticfn void nhl_hookfn(lua_State *, lua_Debug *);
98. #endif /* !SFCTOOL */
99. 
100. #ifndef SFCTOOL
101. static const char *const nhcore_call_names[NUM_NHCORE_CALLS] = {
102.     "start_new_game",
103.     "restore_old_game",
104.     "moveloop_turn",
105.     "game_exit",
106.     "getpos_tip",
107.     "enter_tutorial",
108.     "leave_tutorial",
109. };
110. static boolean nhcore_call_available[NUM_NHCORE_CALLS];
111. #endif
112. 
113. /* internal structure that hangs off L->ud (but use lua_getallocf() )
114.  * Note that we use it for both memory use tracking and instruction counting.
115.  */
116. typedef struct nhl_user_data {
117.     lua_State *L;       /* because the allocator needs it */
118.     uint32_t flags;     /* from nhl_sandbox_info */
119. 
120.     uint32_t memlimit;
121. 
122.     uint32_t steps;     /* current counter */
123.     uint32_t osteps;    /* original steps value */
124.     uint32_t perpcall;  /* per pcall steps value */
125. 
126.     /* stats */
127.     uint32_t statctr;   /* stats step reload count */
128.     int sid;            /* id number (per state) */
129.     const char *name;   /* for stats logging (per pcall) */
130. 
131. #ifdef NHL_SANDBOX
132.     jmp_buf jb;
133. #endif
134. } nhl_user_data;
135. 
136. #ifndef SFCTOOL
137. static lua_State *luapat;   /* instance for file pattern matching */
138. 
139. void
140. l_nhcore_init(void)
141. {
142.     nhl_sandbox_info sbi = { NHL_SB_SAFE, 1 * 1024 * 1024, 0,
143.                              1 * 1024 * 1024 };
144. 
145.     if ((gl.luacore = nhl_init(&sbi)) != 0) {
146.         if (!nhl_loadlua(gl.luacore, "nhcore.lua")) {
147.             gl.luacore = (lua_State *) 0;
148.         } else {
149.             int i;
150. 
151.             for (i = 0; i < NUM_NHCORE_CALLS; i++)
152.                 nhcore_call_available[i] = TRUE;
153.         }
154.     } else
155.         impossible("l_nhcore_init failed");
156. }
157. 
158. void
159. l_nhcore_done(void)
160. {
161.     if (gl.luacore) {
162.         nhl_done(gl.luacore);
163.         gl.luacore = 0;
164.     }
165.     end_luapat();
166. }
167. 
168. void
169. l_nhcore_call(int callidx)
170. {
171.     int ltyp;
172. 
173.     if (callidx < 0 || callidx >= NUM_NHCORE_CALLS || !gl.luacore
174.         || !nhcore_call_available[callidx])
175.         return;
176. 
177.     lua_getglobal(gl.luacore, "nhcore");
178.     if (!lua_istable(gl.luacore, -1)) {
179.         /*impossible("nhcore is not a lua table");*/
180.         nhl_done(gl.luacore);
181.         gl.luacore = 0;
182.         return;
183.     }
184. 
185.     lua_getfield(gl.luacore, -1, nhcore_call_names[callidx]);
186.     ltyp = lua_type(gl.luacore, -1);
187.     if (ltyp == LUA_TFUNCTION) {
188.         nhl_pcall_handle(gl.luacore, 0, 1, "l_nhcore_call", NHLpa_panic);
189.     } else {
190.         /*impossible("nhcore.%s is not a lua function",
191.           nhcore_call_names[callidx]);*/
192.         nhcore_call_available[callidx] = FALSE;
193.     }
194. }
195. 
196. DISABLE_WARNING_UNREACHABLE_CODE
197. 
198. ATTRNORETURN void
199. nhl_error(lua_State *L, const char *msg)
200. {
201.     lua_Debug ar;
202.     char buf[BUFSZ * 2];
203. 
204.     lua_getstack(L, 1, &ar);
205.     lua_getinfo(L, "lS", &ar);
206.     Sprintf(buf, "%s (line %d ", msg, ar.currentline);
207.     Sprintf(eos(buf), "%.*s)",
208.             /* (max length of ar.short_src is actually LUA_IDSIZE
209.                so this is overkill for it, but crucial for ar.source) */
210.             (int) (sizeof buf - (strlen(buf) + sizeof ")")),
211.             ar.short_src); /* (used to be 'ar.source' here) */
212.     lua_pushstring(L, buf);
213. #if 0 /* defined(PANICTRACE) && !defined(NO_SIGNALS) */
214.     panictrace_setsignals(FALSE);
215. #endif
216.     (void) lua_error(L);
217.     /*NOTREACHED*/
218. }
219. 
220. RESTORE_WARNING_UNREACHABLE_CODE
221. 
222. /* Check that parameters are nothing but single table,
223.    or if no parameters given, put empty table there */
224. void
225. lcheck_param_table(lua_State *L)
226. {
227.     int argc = lua_gettop(L);
228. 
229.     if (argc < 1)
230.         lua_createtable(L, 0, 0);
231. 
232.     /* discard any extra arguments passed in */
233.     lua_settop(L, 1);
234. 
235.     luaL_checktype(L, 1, LUA_TTABLE);
236. }
237. 
238. DISABLE_WARNING_UNREACHABLE_CODE
239. 
240. schar
241. get_table_mapchr(lua_State *L, const char *name)
242. {
243.     char *ter;
244.     xint8 typ;
245. 
246.     ter = get_table_str(L, name);
247.     typ = check_mapchr(ter);
248.     if (typ == INVALID_TYPE)
249.         nhl_error(L, "Erroneous map char");
250.     if (ter)
251.         free(ter);
252.     return typ;
253. }
254. 
255. schar
256. get_table_mapchr_opt(lua_State *L, const char *name, schar defval)
257. {
258.     char *ter;
259.     xint8 typ;
260. 
261.     ter = get_table_str_opt(L, name, emptystr);
262.     if (ter && *ter) {
263.         typ = (xint8) check_mapchr(ter);
264.         if (typ == INVALID_TYPE)
265.             nhl_error(L, "Erroneous map char");
266.     } else
267.         typ = (xint8) defval;
268.     if (ter)
269.         free(ter);
270.     return typ;
271. }
272. 
273. short
274. nhl_get_timertype(lua_State *L, int idx)
275. {
276.     /* these are in the same order as enum timeout_types in timeout.h and
277.        ttable timeout_funcs[] in timeout.c, although not spelled the same */
278.     static const char *const timerstr[NUM_TIME_FUNCS + 1] = {
279.         "rot-organic", "rot-corpse", "revive-mon",    "zombify-mon",
280.         "burn-obj",    "hatch-egg",  "fig-transform", "shrink-glob",
281.         "melt-ice",    NULL
282.     };
283.     short ret = luaL_checkoption(L, idx, NULL, timerstr);
284. 
285.     if (ret < 0 || ret >= NUM_TIME_FUNCS)
286.         nhl_error(L, "Unknown timer type");
287.     return ret;
288. }
289. 
290. RESTORE_WARNING_UNREACHABLE_CODE
291. 
292. void
293. nhl_add_table_entry_int(lua_State *L, const char *name, lua_Integer value)
294. {
295.     lua_pushstring(L, name);
296.     lua_pushinteger(L, value);
297.     lua_rawset(L, -3);
298. }
299. 
300. void
301. nhl_add_table_entry_char(lua_State *L, const char *name, char value)
302. {
303.     char buf[2];
304.     Sprintf(buf, "%c", value);
305.     lua_pushstring(L, name);
306.     lua_pushstring(L, buf);
307.     lua_rawset(L, -3);
308. }
309. 
310. void
311. nhl_add_table_entry_str(lua_State *L, const char *name, const char *value)
312. {
313.     lua_pushstring(L, name);
314.     lua_pushstring(L, value);
315.     lua_rawset(L, -3);
316. }
317. void
318. nhl_add_table_entry_bool(lua_State *L, const char *name, boolean value)
319. {
320.     lua_pushstring(L, name);
321.     lua_pushboolean(L, value);
322.     lua_rawset(L, -3);
323. }
324. 
325. void
326. nhl_add_table_entry_region(lua_State *L, const char *name, coordxy x1,
327.                            coordxy y1, coordxy x2, coordxy y2)
328. {
329.     lua_pushstring(L, name);
330.     lua_newtable(L);
331.     nhl_add_table_entry_int(L, "x1", x1);
332.     nhl_add_table_entry_int(L, "y1", y1);
333.     nhl_add_table_entry_int(L, "x2", x2);
334.     nhl_add_table_entry_int(L, "y2", y2);
335.     lua_rawset(L, -3);
336. }
337. 
338. /* converting from special level "map character" to levl location type
339.    and back. order here is important. */
340. static const struct {
341.     char ch;
342.     schar typ;
343. } char2typ[] = {
344.                 { ' ', STONE },
345.                 { '#', CORR },
346.                 { '.', ROOM },
347.                 { '-', HWALL },
348.                 { '-', TLCORNER },
349.                 { '-', TRCORNER },
350.                 { '-', BLCORNER },
351.                 { '-', BRCORNER },
352.                 { '-', CROSSWALL },
353.                 { '-', TUWALL },
354.                 { '-', TDWALL },
355.                 { '-', TLWALL },
356.                 { '-', TRWALL },
357.                 { '-', DBWALL },
358.                 { '|', VWALL },
359.                 { '+', DOOR },
360.                 { 'A', AIR },
361.                 { 'C', CLOUD },
362.                 { 'S', SDOOR },
363.                 { 'H', SCORR },
364.                 { '{', FOUNTAIN },
365.                 { '\\', THRONE },
366.                 { 'K', SINK },
367.                 { '}', MOAT },
368.                 { 'P', POOL },
369.                 { 'L', LAVAPOOL },
370.                 { 'Z', LAVAWALL },
371.                 { 'I', ICE },
372.                 { 'W', WATER },
373.                 { 'T', TREE },
374.                 { 'F', IRONBARS }, /* Fe = iron */
375.                 { 'x', MAX_TYPE }, /* "see-through" */
376.                 { 'B', CROSSWALL }, /* hack: boundary location */
377.                 { 'w', MATCH_WALL }, /* IS_STWALL() */
378.                 { '\0', STONE },
379. };
380. 
381. schar
382. splev_chr2typ(char c)
383. {
384.     int i;
385. 
386.     for (i = 0; char2typ[i].ch; i++)
387.         if (c == char2typ[i].ch)
388.             return char2typ[i].typ;
389.     return (INVALID_TYPE);
390. }
391. 
392. schar
393. check_mapchr(const char *s)
394. {
395.     if (s && strlen(s) == 1)
396.         return splev_chr2typ(s[0]);
397.     return INVALID_TYPE;
398. }
399. 
400. staticfn char
401. splev_typ2chr(schar typ)
402. {
403.     int i;
404. 
405.     for (i = 0; char2typ[i].typ < MAX_TYPE; i++)
406.         if (typ == char2typ[i].typ)
407.             return char2typ[i].ch;
408.     return 'x';
409. }
410. 
411. DISABLE_WARNING_UNREACHABLE_CODE
412. 
413. /* local t = nh.gettrap(x,y); */
414. /* local t = nh.gettrap({ x = 10, y = 10 }); */
415. staticfn int
416. nhl_gettrap(lua_State *L)
417. {
418.     lua_Integer lx, ly;
419.     coordxy x, y;
420. 
421.     if (!nhl_get_xy_params(L, &lx, &ly)) {
422.         nhl_error(L, "Incorrect arguments");
423.         /*NOTREACHED*/
424.         return 0;
425.     }
426.     x = (coordxy) lx;
427.     y = (coordxy) ly;
428.     cvt_to_abscoord(&x, &y);
429. 
430.     if (isok(x, y)) {
431.         struct trap *ttmp = t_at(x, y);
432. 
433.         if (ttmp) {
434.             lua_newtable(L);
435. 
436.             nhl_add_table_entry_int(L, "tx", ttmp->tx);
437.             nhl_add_table_entry_int(L, "ty", ttmp->ty);
438.             nhl_add_table_entry_int(L, "ttyp", ttmp->ttyp);
439.             nhl_add_table_entry_str(L, "ttyp_name",
440.                                     get_trapname_bytype(ttmp->ttyp));
441.             nhl_add_table_entry_bool(L, "tseen", ttmp->tseen);
442.             nhl_add_table_entry_bool(L, "madeby_u", ttmp->madeby_u);
443.             nhl_add_table_entry_bool(L, "once", ttmp->once);
444.             switch (ttmp->ttyp) {
445.             case SQKY_BOARD:
446.                 nhl_add_table_entry_int(L, "tnote", ttmp->tnote);
447.                 break;
448.             case ROLLING_BOULDER_TRAP:
449.                 nhl_add_table_entry_int(L, "launchx", ttmp->launch.x);
450.                 nhl_add_table_entry_int(L, "launchy", ttmp->launch.y);
451.                 nhl_add_table_entry_int(L, "launch2x", ttmp->launch2.x);
452.                 nhl_add_table_entry_int(L, "launch2y", ttmp->launch2.y);
453.                 break;
454.             case PIT:
455.             case SPIKED_PIT:
456.                 nhl_add_table_entry_int(L, "conjoined", ttmp->conjoined);
457.                 break;
458.             }
459.             return 1;
460.         } else {
461.             nhl_error(L, "No trap at location");
462.         }
463.     } else {
464.         nhl_error(L, "Coordinates out of range");
465.     }
466.     return 0;
467. }
468. 
469. /* nh.deltrap(x,y); nh.deltrap({ x = 10, y = 15 }); */
470. staticfn int
471. nhl_deltrap(lua_State *L)
472. {
473.     lua_Integer lx, ly;
474.     coordxy x, y;
475. 
476.     if (!nhl_get_xy_params(L, &lx, &ly)) {
477.         nhl_error(L, "Incorrect arguments");
478.         /*NOTREACHED*/
479.         return 0;
480.     }
481.     x = (coordxy) lx;
482.     y = (coordxy) ly;
483.     cvt_to_abscoord(&x, &y);
484. 
485.     if (isok(x, y)) {
486.         struct trap *ttmp = t_at(x, y);
487. 
488.         if (ttmp)
489.             deltrap(ttmp);
490.     }
491.     return 0;
492. }
493. 
494. RESTORE_WARNING_UNREACHABLE_CODE
495. 
496. /* get parameters (XX,YY) or ({ x = XX, y = YY }) or ({ XX, YY }),
497.    and set the x and y values.
498.    return TRUE if there are such params in the stack.
499.    Note that this does not adjust the values of x and y at all from what is
500.    specified in the level file; so, it returns absolute coordinates rather
501.    than map-relative coordinates. Callers of this function must decide if
502.    they want to interpret the values as absolute or as map-relative, and
503.    adjust accordingly.
504.  */
505. boolean
506. nhl_get_xy_params(lua_State *L, lua_Integer *x, lua_Integer *y)
507. {
508.     int argc = lua_gettop(L);
509.     boolean ret = FALSE;
510. 
511.     if (argc == 2) {
512.         *x = lua_tointeger(L, 1);
513.         *y = lua_tointeger(L, 2);
514.         ret = TRUE;
515.     } else if (argc == 1 && lua_type(L, 1) == LUA_TTABLE) {
516.         lua_Integer ax, ay;
517. 
518.         ret = get_coord(L, 1, &ax, &ay);
519.         *x = ax;
520.         *y = ay;
521.     }
522.     return ret;
523. }
524. 
525. DISABLE_WARNING_UNREACHABLE_CODE
526. 
527. /* local loc = nh.getmap(x,y); */
528. /* local loc = nh.getmap({ x = 10, y = 35 }); */
529. staticfn int
530. nhl_getmap(lua_State *L)
531. {
532.     lua_Integer lx, ly;
533.     coordxy x, y;
534. 
535.     if (!nhl_get_xy_params(L, &lx, &ly)) {
536.         nhl_error(L, "Incorrect arguments");
537.         return 0;
538.     }
539.     x = (coordxy) lx;
540.     y = (coordxy) ly;
541.     cvt_to_abscoord(&x, &y);
542. 
543.     if (isok(x, y)) {
544.         char buf[BUFSZ];
545.         lua_newtable(L);
546. 
547.         /* FIXME: some should be boolean values */
548.         nhl_add_table_entry_int(L, "glyph", levl[x][y].glyph);
549.         nhl_add_table_entry_int(L, "typ", levl[x][y].typ);
550.         nhl_add_table_entry_str(L, "typ_name",
551.                                 levltyp_to_name(levl[x][y].typ));
552.         Sprintf(buf, "%c", splev_typ2chr(levl[x][y].typ));
553.         nhl_add_table_entry_str(L, "mapchr", buf);
554.         nhl_add_table_entry_int(L, "seenv", levl[x][y].seenv);
555.         nhl_add_table_entry_bool(L, "horizontal", levl[x][y].horizontal);
556.         nhl_add_table_entry_bool(L, "lit", levl[x][y].lit);
557.         nhl_add_table_entry_bool(L, "waslit", levl[x][y].waslit);
558.         nhl_add_table_entry_int(L, "roomno", levl[x][y].roomno);
559.         nhl_add_table_entry_bool(L, "edge", levl[x][y].edge);
560.         nhl_add_table_entry_bool(L, "candig", levl[x][y].candig);
561. 
562.         nhl_add_table_entry_bool(L, "has_trap", t_at(x, y) ? 1 : 0);
563. 
564.         /* TODO: FIXME: levl[x][y].flags */
565. 
566.         lua_pushliteral(L, "flags");
567.         lua_newtable(L);
568. 
569.         if (IS_DOOR(levl[x][y].typ)) {
570.             nhl_add_table_entry_bool(L, "nodoor",
571.                                      (levl[x][y].flags == D_NODOOR));
572.             nhl_add_table_entry_bool(L, "broken",
573.                                      (levl[x][y].flags & D_BROKEN));
574.             nhl_add_table_entry_bool(L, "isopen",
575.                                      (levl[x][y].flags & D_ISOPEN));
576.             nhl_add_table_entry_bool(L, "closed",
577.                                      (levl[x][y].flags & D_CLOSED));
578.             nhl_add_table_entry_bool(L, "locked",
579.                                      (levl[x][y].flags & D_LOCKED));
580.             nhl_add_table_entry_bool(L, "trapped",
581.                                      (levl[x][y].flags & D_TRAPPED));
582.         } else if (IS_ALTAR(levl[x][y].typ)) {
583.             /* TODO: bits 0, 1, 2 */
584.             nhl_add_table_entry_bool(L, "shrine",
585.                                      (levl[x][y].flags & AM_SHRINE));
586.         } else if (IS_THRONE(levl[x][y].typ)) {
587.             nhl_add_table_entry_bool(L, "looted",
588.                                      (levl[x][y].flags & T_LOOTED));
589.         } else if (levl[x][y].typ == TREE) {
590.             nhl_add_table_entry_bool(L, "looted",
591.                                      (levl[x][y].flags & TREE_LOOTED));
592.             nhl_add_table_entry_bool(L, "swarm",
593.                                      (levl[x][y].flags & TREE_SWARM));
594.         } else if (IS_FOUNTAIN(levl[x][y].typ)) {
595.             nhl_add_table_entry_bool(L, "looted",
596.                                      (levl[x][y].flags & F_LOOTED));
597.             nhl_add_table_entry_bool(L, "warned",
598.                                      (levl[x][y].flags & F_WARNED));
599.         } else if (IS_SINK(levl[x][y].typ)) {
600.             nhl_add_table_entry_bool(L, "pudding",
601.                                      (levl[x][y].flags & S_LPUDDING));
602.             nhl_add_table_entry_bool(L, "dishwasher",
603.                                      (levl[x][y].flags & S_LDWASHER));
604.             nhl_add_table_entry_bool(L, "ring", (levl[x][y].flags & S_LRING));
605.         }
606.         /* TODO: drawbridges, walls, ladders, room=>ICED_xxx */
607. 
608.         lua_settable(L, -3);
609. 
610.         return 1;
611.     } else {
612.         /* TODO: return zerorm instead? */
613.         nhl_error(L, "Coordinates out of range");
614.         return 0;
615.     }
616. }
617. 
618. /* impossible("Error!") */
619. staticfn int
620. nhl_impossible(lua_State *L)
621. {
622.     int argc = lua_gettop(L);
623. 
624.     if (argc == 1)
625.         impossible("%s", luaL_checkstring(L, 1));
626.     else
627.         nhl_error(L, "Wrong args");
628.     return 0;
629. }
630. 
631. /* pline("It hits!") */
632. /* pline("It hits!", true) */
633. staticfn int
634. nhl_pline(lua_State *L)
635. {
636.     int argc = lua_gettop(L);
637. 
638.     if (argc == 1 || argc == 2) {
639.         pline("%s", luaL_checkstring(L, 1));
640.         if (lua_toboolean(L, 2))
641.             display_nhwindow(WIN_MESSAGE, TRUE); /* --more-- */
642.     } else
643.         nhl_error(L, "Wrong args");
644. 
645.     return 0;
646. }
647. 
648. /* verbalize("Fool!") */
649. staticfn int
650. nhl_verbalize(lua_State *L)
651. {
652.     int argc = lua_gettop(L);
653. 
654.     if (argc == 1)
655.         verbalize("%s", luaL_checkstring(L, 1));
656.     else
657.         nhl_error(L, "Wrong args");
658. 
659.     return 0;
660. }
661. 
662. /* parse_config("OPTIONS=!color") */
663. staticfn int
664. nhl_parse_config(lua_State *L)
665. {
666.     int argc = lua_gettop(L);
667. 
668.     if (argc == 1)
669.         parse_conf_str(luaL_checkstring(L, 1), parse_config_line);
670.     else
671.         nhl_error(L, "Wrong args");
672. 
673.     return 0;
674. }
675. 
676. /* local windowtype = get_config("windowtype"); */
677. staticfn int
678. nhl_get_config(lua_State *L)
679. {
680.     int argc = lua_gettop(L);
681. 
682.     if (argc == 1) {
683.         lua_pushstring(L, get_option_value(luaL_checkstring(L, 1), TRUE));
684.         return 1;
685.     } else
686.         nhl_error(L, "Wrong args");
687. 
688.     return 0;
689. }
690. 
691. /*
692.   str = getlin("What do you want to call this dungeon level?");
693.  */
694. staticfn int
695. nhl_getlin(lua_State *L)
696. {
697.     int argc = lua_gettop(L);
698. 
699.     if (argc == 1) {
700.         const char *prompt = luaL_checkstring(L, 1);
701.         char buf[BUFSZ];
702. 
703.         getlin(prompt, buf);
704.         lua_pushstring(L, buf);
705.         return 1;
706.     }
707. 
708.     nhl_error(L, "Wrong args");
709.     /*NOTREACHED*/
710.     return 0;
711. }
712. 
713. /*
714.  selected = menu("prompt",default,pickX,{"a"="option a", "b"="option b",...})
715.  pickX = 0,1,2, or "none", "one", "any" (PICK_X in code)
716. 
717.  selected = menu("prompt", default, pickX,
718.                  {{key:"a", text:"option a"},{key:"b", text:"option b"},... })
719.  */
720. staticfn int
721. nhl_menu(lua_State *L)
722. {
723.     static const char *const pickX[] = { "none", "one", "any" }; /* PICK_x */
724.     int argc = lua_gettop(L);
725.     const char *prompt;
726.     const char *defval = "";
727.     int pick = PICK_ONE, pick_cnt;
728.     winid tmpwin;
729.     anything any;
730.     menu_item *picks = (menu_item *) 0;
731.     int clr = NO_COLOR;
732. 
733.     if (argc < 2 || argc > 4) {
734.         nhl_error(L, "Wrong args");
735.         /*NOTREACHED*/
736.         return 0;
737.     }
738. 
739.     prompt = luaL_checkstring(L, 1);
740.     if (lua_isstring(L, 2))
741.         defval = luaL_checkstring(L, 2);
742.     if (lua_isstring(L, 3))
743.         pick = luaL_checkoption(L, 3, "one", pickX);
744.     luaL_checktype(L, argc, LUA_TTABLE);
745. 
746.     tmpwin = create_nhwindow(NHW_MENU);
747.     start_menu(tmpwin, MENU_BEHAVE_STANDARD);
748. 
749.     lua_pushnil(L); /* first key */
750.     while (lua_next(L, argc) != 0) {
751.         const char *str = "";
752.         const char *key = "";
753. 
754.         /* key @ index -2, value @ index -1 */
755.         if (lua_istable(L, -1)) {
756.             lua_pushliteral(L, "key");
757.             lua_gettable(L, -2);
758.             key = lua_tostring(L, -1);
759.             lua_pop(L, 1);
760. 
761.             lua_pushliteral(L, "text");
762.             lua_gettable(L, -2);
763.             str = lua_tostring(L, -1);
764.             lua_pop(L, 1);
765. 
766.             /* TODO: glyph, attr, accel, group accel (all optional) */
767.         } else if (lua_isstring(L, -1)) {
768.             str = luaL_checkstring(L, -1);
769.             key = luaL_checkstring(L, -2);
770.         }
771. 
772.         any = cg.zeroany;
773.         if (*key)
774.             any.a_char = key[0];
775.         add_menu(tmpwin, &nul_glyphinfo, &any, 0, 0, ATR_NONE, clr, str,
776.                  (*defval && *key && defval[0] == key[0])
777.                      ? MENU_ITEMFLAGS_SELECTED
778.                      : MENU_ITEMFLAGS_NONE);
779. 
780.         lua_pop(L, 1); /* removes 'value'; keeps 'key' for next iteration */
781.     }
782. 
783.     end_menu(tmpwin, prompt);
784.     pick_cnt = select_menu(tmpwin, pick, &picks);
785.     destroy_nhwindow(tmpwin);
786. 
787.     if (pick_cnt > 0) {
788.         char buf[2];
789.         buf[0] = picks[0].item.a_char;
790. 
791.         if (pick == PICK_ONE && pick_cnt > 1 && *defval
792.             && defval[0] == picks[0].item.a_char)
793.             buf[0] = picks[1].item.a_char;
794. 
795.         buf[1] = '\0';
796.         lua_pushstring(L, buf);
797.         /* TODO: pick any */
798.     } else {
799.         char buf[2];
800.         buf[0] = defval[0];
801.         buf[1] = '\0';
802.         lua_pushstring(L, buf);
803.     }
804. 
805.     return 1;
806. }
807. 
808. /* text("foo\nbar\nbaz") */
809. staticfn int
810. nhl_text(lua_State *L)
811. {
812.     int argc = lua_gettop(L);
813. 
814.     if (argc > 0) {
815.         menu_item *picks = (menu_item *) 0;
816.         winid tmpwin;
817. 
818.         tmpwin = create_nhwindow(NHW_MENU);
819.         start_menu(tmpwin, MENU_BEHAVE_STANDARD);
820. 
821.         while (lua_gettop(L) > 0) {
822.             char *ostr = dupstr(luaL_checkstring(L, 1));
823.             char *ptr, *str = ostr;
824.             char *lstr = str + strlen(str) - 1;
825. 
826.             do {
827.                 char *nlp = strchr(str, '\n');
828. 
829.                 if (nlp && (nlp - str) <= 76) {
830.                     ptr = nlp;
831.                 } else {
832.                     ptr = str + 76;
833.                     if (ptr > lstr)
834.                         ptr = lstr;
835.                 }
836.                 while ((ptr > str) && !(*ptr == ' ' || *ptr == '\n'))
837.                     ptr--;
838.                 *ptr = '\0';
839.                 add_menu_str(tmpwin, str);
840.                 str = ptr + 1;
841.             } while (*str && str <= lstr);
842.             lua_pop(L, 1);
843.             free(ostr);
844.         }
845. 
846.         end_menu(tmpwin, (char *) 0);
847.         (void) select_menu(tmpwin, PICK_NONE, &picks);
848.         destroy_nhwindow(tmpwin);
849.     }
850.     return 0;
851. }
852. 
853. /* makeplural("zorkmid") */
854. staticfn int
855. nhl_makeplural(lua_State *L)
856. {
857.     int argc = lua_gettop(L);
858. 
859.     if (argc == 1)
860.         lua_pushstring(L, makeplural(luaL_checkstring(L, 1)));
861.     else
862.         nhl_error(L, "Wrong args");
863. 
864.     return 1;
865. }
866. 
867. /* makesingular("zorkmids") */
868. staticfn int
869. nhl_makesingular(lua_State *L)
870. {
871.     int argc = lua_gettop(L);
872. 
873.     if (argc == 1)
874.         lua_pushstring(L, makesingular(luaL_checkstring(L, 1)));
875.     else
876.         nhl_error(L, "Wrong args");
877. 
878.     return 1;
879. }
880. 
881. /* s_suffix("foo") */
882. staticfn int
883. nhl_s_suffix(lua_State *L)
884. {
885.     int argc = lua_gettop(L);
886. 
887.     if (argc == 1)
888.         lua_pushstring(L, s_suffix(luaL_checkstring(L, 1)));
889.     else
890.         nhl_error(L, "Wrong args");
891. 
892.     return 1;
893. }
894. 
895. /* ing_suffix("foo") */
896. staticfn int
897. nhl_ing_suffix(lua_State *L)
898. {
899.     int argc = lua_gettop(L);
900. 
901.     if (argc == 1)
902.         lua_pushstring(L, ing_suffix(luaL_checkstring(L, 1)));
903.     else
904.         nhl_error(L, "Wrong args");
905. 
906.     return 1;
907. }
908. 
909. /* an("foo") */
910. staticfn int
911. nhl_an(lua_State *L)
912. {
913.     int argc = lua_gettop(L);
914. 
915.     if (argc == 1)
916.         lua_pushstring(L, an(luaL_checkstring(L, 1)));
917.     else
918.         nhl_error(L, "Wrong args");
919. 
920.     return 1;
921. }
922. 
923. /* rn2(10) */
924. staticfn int
925. nhl_rn2(lua_State *L)
926. {
927.     int argc = lua_gettop(L);
928. 
929.     if (argc == 1)
930.         lua_pushinteger(L, rn2((int) luaL_checkinteger(L, 1)));
931.     else
932.         nhl_error(L, "Wrong args");
933. 
934.     return 1;
935. }
936. 
937. /* random(10);  -- is the same as rn2(10); */
938. /* random(5,8); -- same as 5 + rn2(8); */
939. staticfn int
940. nhl_random(lua_State *L)
941. {
942.     int argc = lua_gettop(L);
943. 
944.     if (argc == 1)
945.         lua_pushinteger(L, rn2((int) luaL_checkinteger(L, 1)));
946.     else if (argc == 2)
947.         lua_pushinteger(L, luaL_checkinteger(L, 1)
948.                                + rn2((int) luaL_checkinteger(L, 2)));
949.     else
950.         nhl_error(L, "Wrong args");
951. 
952.     return 1;
953. }
954. 
955. /* level_difficulty() */
956. staticfn int
957. nhl_level_difficulty(lua_State *L)
958. {
959.     int argc = lua_gettop(L);
960.     if (argc == 0) {
961.         lua_pushinteger(L, level_difficulty());
962.     } else {
963.         nhl_error(L, "level_difficulty should not have any args");
964.     }
965.     return 1;
966. }
967. 
968. /* local x = nh.is_genocided("vampire") */
969. staticfn int
970. nhl_is_genocided(lua_State *L)
971. {
972.     int argc = lua_gettop(L);
973. 
974.     if (argc == 1) {
975.         const char *paramstr = luaL_checkstring(L, 1);
976.         int mgend;
977.         int i = name_to_mon(paramstr, &mgend);
978. 
979.         lua_pushboolean(L, (i != NON_PM)
980.                         && (svm.mvitals[i].mvflags & G_GENOD)
981.                         ? TRUE : FALSE);
982.     } else {
983.         nhl_error(L, "Wrong args");
984.     }
985.     return 1;
986. }
987. 
988. /* local debug_themerm = nh.debug_themerm(isfill)
989.  * if isfill is false, returns value of env variable THEMERM
990.  * if isfill is true,  returns value of env variable THEMERMFILL
991.  * return nil if not in wizard mode or the variable isn't set */
992. staticfn int
993. nhl_get_debug_themerm_name(lua_State *L)
994. {
995.     int argc = lua_gettop(L);
996.     if (argc == 1) {
997.         char *dbg_themerm = (char *) 0;
998.         boolean is_fill = lua_toboolean(L, 1);
999.         lua_pop(L, 1);
1000.         if (wizard)
1001.             dbg_themerm = getenv(is_fill ? "THEMERMFILL" : "THEMERM");
1002.         if (!dbg_themerm || !*dbg_themerm) {
1003.             lua_pushnil(L);
1004.         } else {
1005.             lua_pushstring(L, dbg_themerm);
1006.         }
1007.     } else {
1008.         nhl_error(L, "debug_themerm should have 1 boolean arg");
1009.     }
1010.     return 1;
1011. }
1012. 
1013. RESTORE_WARNING_UNREACHABLE_CODE
1014. 
1015. /* get mandatory integer value from table */
1016. int
1017. get_table_int(lua_State *L, const char *name)
1018. {
1019.     int ret;
1020. 
1021.     lua_getfield(L, -1, name);
1022.     ret = (int) luaL_checkinteger(L, -1);
1023.     lua_pop(L, 1);
1024.     return ret;
1025. }
1026. 
1027. /* get optional integer value from table */
1028. int
1029. get_table_int_opt(lua_State *L, const char *name, int defval)
1030. {
1031.     int ret = defval;
1032. 
1033.     lua_getfield(L, -1, name);
1034.     if (!lua_isnil(L, -1)) {
1035.         ret = (int) luaL_checkinteger(L, -1);
1036.     }
1037.     lua_pop(L, 1);
1038.     return ret;
1039. }
1040. 
1041. char *
1042. get_table_str(lua_State *L, const char *name)
1043. {
1044.     char *ret;
1045. 
1046.     lua_getfield(L, -1, name);
1047.     ret = dupstr(luaL_checkstring(L, -1));
1048.     lua_pop(L, 1);
1049.     return ret;
1050. }
1051. 
1052. /* get optional string value from table.
1053.    return value must be freed by caller. */
1054. char *
1055. get_table_str_opt(lua_State *L, const char *name, char *defval)
1056. {
1057.     const char *ret;
1058.     int ltyp;
1059. 
1060.     lua_getfield(L, -1, name);
1061.     ltyp = lua_type(L, -1);
1062.     if (ltyp == LUA_TSTRING || ltyp == LUA_TNIL) {
1063.         ret = luaL_optstring(L, -1, defval);
1064.     } else if (ltyp == LUA_TFUNCTION) {
1065.         nhl_pcall_handle(L, 0, 1, "get_table_str_opt", NHLpa_panic);
1066.         ret = luaL_optstring(L, -1, defval);
1067.     } else {
1068.         nhl_error(L, "get_table_str_opt: no string");
1069.     }
1070.     if (ret) {
1071.         lua_pop(L, 1);
1072.         return dupstr(ret);
1073.     }
1074.     lua_pop(L, 1);
1075.     return NULL;
1076. }
1077. 
1078. int
1079. get_table_boolean(lua_State *L, const char *name)
1080. {
1081.     static const char *const boolstr[] = {
1082.         "true", "false", "yes", "no", NULL
1083.     };
1084.     /* static const int boolstr2i[] = { TRUE, FALSE, TRUE, FALSE, -1 }; */
1085.     int ltyp;
1086.     int ret = -1;
1087. 
1088.     lua_getfield(L, -1, name);
1089.     ltyp = lua_type(L, -1);
1090.     if (ltyp == LUA_TSTRING) {
1091.         ret = luaL_checkoption(L, -1, NULL, boolstr);
1092.         /* nhUse(boolstr2i[0]); */
1093.     } else if (ltyp == LUA_TBOOLEAN) {
1094.         ret = lua_toboolean(L, -1);
1095.     } else if (ltyp == LUA_TNUMBER) {
1096.         ret = (int) luaL_checkinteger(L, -1);
1097.         if (ret < 0 || ret > 1)
1098.             ret = -1;
1099.     }
1100.     lua_pop(L, 1);
1101.     if (ret == -1)
1102.         nhl_error(L, "Expected a boolean");
1103.     return ret;
1104. }
1105. 
1106. int
1107. get_table_boolean_opt(lua_State *L, const char *name, int defval)
1108. {
1109.     int ret = defval;
1110. 
1111.     lua_getfield(L, -1, name);
1112.     if (lua_type(L, -1) != LUA_TNIL) {
1113.         lua_pop(L, 1);
1114.         return get_table_boolean(L, name);
1115.     }
1116.     lua_pop(L, 1);
1117.     return ret;
1118. }
1119. 
1120. /* opts[] is a null-terminated list */
1121. int
1122. get_table_option(lua_State *L,
1123.                  const char *name,
1124.                  const char *defval,
1125.                  const char *const opts[])
1126. {
1127.     int ret;
1128. 
1129.     lua_getfield(L, -1, name);
1130.     ret = luaL_checkoption(L, -1, defval, opts);
1131.     lua_pop(L, 1);
1132.     return ret;
1133. }
1134. 
1135. #ifdef DUMPLOG
1136. /* local fname = dump_fmtstr("/tmp/nethack.%n.%d.log"); */
1137. staticfn int
1138. nhl_dump_fmtstr(lua_State *L)
1139. {
1140.     int argc = lua_gettop(L);
1141.     char buf[512];
1142. 
1143.     if (argc == 1)
1144.         lua_pushstring(L, dump_fmtstr(luaL_checkstring(L, 1), buf, TRUE));
1145.     else
1146.         nhl_error(L, "Expected a string parameter");
1147.     return 1;
1148. }
1149. #endif /* DUMPLOG */
1150. 
1151. /* local dungeon_name = dnum_name(u.dnum); */
1152. staticfn int
1153. nhl_dnum_name(lua_State *L)
1154. {
1155.     int argc = lua_gettop(L);
1156. 
1157.     if (argc == 1) {
1158.         lua_Integer dnum = luaL_checkinteger(L, 1);
1159. 
1160.         if (dnum >= 0 && dnum < svn.n_dgns)
1161.             lua_pushstring(L, svd.dungeons[dnum].dname);
1162.         else
1163.             lua_pushstring(L, "");
1164.     } else
1165.         nhl_error(L, "Expected an integer parameter");
1166.     return 1;
1167. }
1168. 
1169. /* return gender-neutral monster type name by integer value,
1170.    or empty string if outside LOW_PM - HIGH_PM range */
1171. /* local montypename = int_to_pmname(12); */
1172. staticfn int
1173. nhl_int_to_pm_name(lua_State *L)
1174. {
1175.     int argc = lua_gettop(L);
1176. 
1177.     if (argc == 1) {
1178.         lua_Integer i = luaL_checkinteger(L, 1);
1179. 
1180.         if (i >= LOW_PM && i <= HIGH_PM)
1181.             lua_pushstring(L, mons[i].pmnames[NEUTRAL]);
1182.         else
1183.             lua_pushstring(L, "");
1184.     } else
1185.         nhl_error(L, "Expected an integer parameter");
1186.     return 1;
1187. }
1188. 
1189. /* convert integer to object type name and class */
1190. /* local oname,oclass = int_to_objname(25); */
1191. staticfn int
1192. nhl_int_to_obj_name(lua_State *L)
1193. {
1194.     int argc = lua_gettop(L);
1195. 
1196.     if (argc == 1) {
1197.         char buf[8];
1198.         lua_Integer i = luaL_checkinteger(L, 1);
1199. 
1200.         if (i >= 0 && i < NUM_OBJECTS && OBJ_NAME(objects[i])) {
1201.             lua_pushstring(L, OBJ_NAME(objects[i]));
1202.             buf[0] = def_oc_syms[(int)objects[i].oc_class].sym;
1203.             buf[1] = '\0';
1204.             lua_pushstring(L, buf);
1205.         } else {
1206.             lua_pushstring(L, "");
1207.             lua_pushstring(L, "");
1208.         }
1209.     } else
1210.         nhl_error(L, "Expected an integer parameter");
1211.     return 2;
1212. }
1213. 
1214. DISABLE_WARNING_UNREACHABLE_CODE
1215. /* because nhl_error() does not return */
1216. 
1217. /* set or get variables which are saved and restored along with the game.
1218.    nh.variable("test", 10);
1219.    local ten = nh.variable("test"); */
1220. staticfn int
1221. nhl_variable(lua_State *L)
1222. {
1223.     int argc = lua_gettop(L);
1224.     int typ;
1225.     const char *key;
1226. 
1227.     if (!gl.luacore) {
1228.         panic("nh luacore not inited");
1229.         /*NOTREACHED*/
1230.         return 0;
1231.     }
1232. 
1233.     lua_getglobal(gl.luacore, "nh_lua_variables");
1234.     if (!lua_istable(gl.luacore, -1)) {
1235.         impossible("nh_lua_variables is not a lua table");
1236.         return 0;
1237.     }
1238. 
1239.     if (argc == 1) {
1240.         key = luaL_checkstring(L, 1);
1241. 
1242.         lua_getfield(gl.luacore, -1, key);
1243.         typ = lua_type(gl.luacore, -1);
1244.         if (typ == LUA_TSTRING)
1245.             lua_pushstring(L, lua_tostring(gl.luacore, -1));
1246.         else if (typ == LUA_TNIL)
1247.             lua_pushnil(L);
1248.         else if (typ == LUA_TBOOLEAN)
1249.             lua_pushboolean(L, lua_toboolean(gl.luacore, -1));
1250.         else if (typ == LUA_TNUMBER)
1251.             lua_pushinteger(L, lua_tointeger(gl.luacore, -1));
1252.         else if (typ == LUA_TTABLE) {
1253.             lua_getglobal(gl.luacore, "nh_get_variables_string");
1254.             lua_pushvalue(gl.luacore, -2);
1255.             nhl_pcall_handle(gl.luacore, 1, 1, "nhl_variable", NHLpa_panic);
1256.             luaL_loadstring(L, lua_tostring(gl.luacore, -1));
1257.             nhl_pcall_handle(L, 0, 1, "nhl_variable-1", NHLpa_panic);
1258.         } else
1259.             nhl_error(L, "Cannot get variable of that type");
1260.         return 1;
1261.     } else if (argc == 2) {
1262.         /* set nh_lua_variables[key] = value;
1263.            nh.variable("key", value); */
1264.         key = luaL_checkstring(L, 1);
1265.         //pline("SETVAR:%s", key);
1266.         typ = lua_type(L, -1);
1267. 
1268.         if (typ == LUA_TSTRING) {
1269.             lua_pushstring(gl.luacore, lua_tostring(L, -1));
1270.             lua_setfield(gl.luacore, -2, key);
1271.         } else if (typ == LUA_TNIL) {
1272.             lua_pushnil(gl.luacore);
1273.             lua_setfield(gl.luacore, -2, key);
1274.         } else if (typ == LUA_TBOOLEAN) {
1275.             lua_pushboolean(gl.luacore, lua_toboolean(L, -1));
1276.             lua_setfield(gl.luacore, -2, key);
1277.         } else if (typ == LUA_TNUMBER) {
1278.             lua_pushinteger(gl.luacore, lua_tointeger(L, -1));
1279.             lua_setfield(gl.luacore, -2, key);
1280.         } else if (typ == LUA_TTABLE) {
1281.             lua_getglobal(L, "nh_set_variables_string");
1282.             lua_pushstring(L, key);
1283.             lua_pushvalue(L, -3); /* copy value to top */
1284.             nhl_pcall_handle(L, 2, 1, "nhl_variable-2", NHLpa_panic);
1285.             luaL_loadstring(gl.luacore, lua_tostring(L, -1));
1286.             nhl_pcall_handle(gl.luacore, 0, 0, "nhl_variable-3", NHLpa_panic);
1287.         } else
1288.             nhl_error(L, "Cannot set variable of that type");
1289.         return 0;
1290.     } else
1291.         nhl_error(L, "Wrong number of arguments");
1292.     return 1;
1293. }
1294. 
1295. /* return nh_lua_variable lua table as a string */
1296. char *
1297. get_nh_lua_variables(void)
1298. {
1299.     char *key = NULL;
1300. 
1301.     if (!gl.luacore) {
1302.         panic("nh luacore not inited");
1303.         /*NOTREACHED*/
1304.         return key;
1305.     }
1306.     lua_getglobal(gl.luacore, "get_variables_string");
1307.     if (lua_type(gl.luacore, -1) == LUA_TFUNCTION) {
1308.         if (nhl_pcall_handle(gl.luacore, 0, 1, "get_nh_lua_variables",
1309.                              NHLpa_impossible)) {
1310.             return key;
1311.         }
1312.         key = dupstr(lua_tostring(gl.luacore, -1));
1313.     }
1314.     lua_pop(gl.luacore, 1);
1315.     return key;
1316. }
1317. 
1318. RESTORE_WARNING_UNREACHABLE_CODE
1319. 
1320. #endif /* !SFCTOOL */
1321. 
1322. #ifdef SFCTOOL
1323. char *lua_data;
1324. #endif
1325. 
1326. /* save nh_lua_variables table to file */
1327. void
1328. save_luadata(NHFILE *nhfp)
1329. {
1330.     unsigned lua_data_len;
1331. #ifndef SFCTOOL
1332.     char *lua_data = get_nh_lua_variables(); /* note: '\0' terminated */
1333. #endif
1334. 
1335.     if (!lua_data)
1336.         lua_data = dupstr(emptystr);
1337.     lua_data_len = Strlen(lua_data) + 1; /* +1: include the terminator */
1338.     Sfo_unsigned(nhfp, &lua_data_len, "luadata-lua_data_len");
1339.     Sfo_char(nhfp, lua_data, "luadata", lua_data_len);
1340.     free(lua_data);
1341. }
1342. 
1343. /* restore nh_lua_variables table from file */
1344. void
1345. restore_luadata(NHFILE *nhfp)
1346. {
1347.     unsigned lua_data_len = 0;
1348. #ifndef SFCTOOL
1349.     char *lua_data;
1350. #endif /* !SFCTOOL */
1351. 
1352.     Sfi_unsigned(nhfp, &lua_data_len, "luadata-lua_data_len");
1353.     lua_data = (char *) alloc(lua_data_len);
1354.     Sfi_char(nhfp, lua_data, "luadata", lua_data_len);
1355. 
1356. #ifndef SFCTOOL
1357.     if (!gl.luacore)
1358.         l_nhcore_init();
1359.     luaL_loadstring(gl.luacore, lua_data);
1360.     free(lua_data);
1361.     nhl_pcall_handle(gl.luacore, 0, 0, "restore_luadata", NHLpa_panic);
1362. #endif /* !SFCTOOL */
1363. }
1364. 
1365. #ifndef SFCTOOL
1366. 
1367. /* local stairs = stairways(); */
1368. staticfn int
1369. nhl_stairways(lua_State *L)
1370. {
1371.     stairway *tmp = gs.stairs;
1372.     int i = 1; /* lua arrays should start at 1 */
1373. 
1374.     lua_newtable(L);
1375. 
1376.     while (tmp) {
1377.         lua_pushinteger(L, i);
1378.         lua_newtable(L);
1379. 
1380.         nhl_add_table_entry_bool(L, "up", tmp->up);
1381.         nhl_add_table_entry_bool(L, "ladder", tmp->isladder);
1382.         nhl_add_table_entry_int(L, "x", tmp->sx);
1383.         nhl_add_table_entry_int(L, "y", tmp->sy);
1384.         nhl_add_table_entry_int(L, "dnum", tmp->tolev.dnum);
1385.         nhl_add_table_entry_int(L, "dlevel", tmp->tolev.dlevel);
1386. 
1387.         lua_settable(L, -3);
1388. 
1389.         tmp = tmp->next;
1390.         i++;
1391.     }
1392. 
1393.     return 1;
1394. }
1395. 
1396. /*
1397.   test( { x = 123, y = 456 } );
1398. */
1399. staticfn int
1400. nhl_test(lua_State *L)
1401. {
1402.     coordxy x, y;
1403.     char *name, Player[] = "Player";
1404. 
1405.     /* discard any extra arguments passed in */
1406.     lua_settop(L, 1);
1407. 
1408.     luaL_checktype(L, 1, LUA_TTABLE);
1409. 
1410.     x = (coordxy) get_table_int(L, "x");
1411.     y = (coordxy) get_table_int(L, "y");
1412.     name = get_table_str_opt(L, "name", Player);
1413. 
1414.     pline("TEST:{ x=%i, y=%i, name=\"%s\" }", (int) x, (int) y, name);
1415. 
1416.     free(name);
1417. 
1418.     return 1;
1419. }
1420. 
1421. /* push a key into command queue */
1422. /* nh.pushkey("i"); */
1423. staticfn int
1424. nhl_pushkey(lua_State *L)
1425. {
1426.     int argc = lua_gettop(L);
1427. 
1428.     if (argc == 1) {
1429.         const char *key = luaL_checkstring(L, 1);
1430. 
1431.         while (*key) {
1432.             cmdq_add_key(CQ_CANNED, *key);
1433.             key++;
1434.         }
1435.     }
1436. 
1437.     return 0;
1438. }
1439. 
1440. /* do a turn of moveloop, or until gm.multi is done if param is true. */
1441. /* nh.doturn(); nh.doturn(true); */
1442. staticfn int
1443. nhl_doturn(lua_State *L)
1444. {
1445.     int argc = lua_gettop(L);
1446.     boolean domulti = FALSE;
1447. 
1448.     if (argc == 1)
1449.         domulti = lua_toboolean(L, 1);
1450. 
1451.     do {
1452.         moveloop_core();
1453.     } while (domulti && gm.multi);
1454. 
1455.     return 0;
1456. }
1457. 
1458. /* set debugging flags. debugging use only, of course. */
1459. /* nh.debug_flags({ mongen = false,
1460.                     hunger = false,
1461.                     overwrite_stairs = true }); */
1462. staticfn int
1463. nhl_debug_flags(lua_State *L)
1464. {
1465.     int val;
1466. 
1467.     lcheck_param_table(L);
1468. 
1469.     /* disable monster generation */
1470.     val = get_table_boolean_opt(L, "mongen", -1);
1471.     if (val != -1) {
1472.         iflags.debug_mongen = !(boolean) val; /* value in lua is negated */
1473.         if (iflags.debug_mongen) {
1474.             struct monst *mtmp, *mtmp2;
1475. 
1476.             for (mtmp = fmon; mtmp; mtmp = mtmp2) {
1477.                 mtmp2 = mtmp->nmon;
1478.                 if (DEADMONSTER(mtmp))
1479.                     continue;
1480.                 mongone(mtmp);
1481.             }
1482.         }
1483.     }
1484. 
1485.     /* prevent hunger */
1486.     val = get_table_boolean_opt(L, "hunger", -1);
1487.     if (val != -1) {
1488.         iflags.debug_hunger = !(boolean) val; /* value in lua is negated */
1489.     }
1490. 
1491.     /* allow overwriting stairs */
1492.     val = get_table_boolean_opt(L, "overwrite_stairs", -1);
1493.     if (val != -1) {
1494.         iflags.debug_overwrite_stairs = (boolean) val;
1495.     }
1496. 
1497.     /* prevent pline going out to the UI */
1498.     val = get_table_boolean_opt(L, "prevent_pline", -1);
1499.     if (val != -1) {
1500.         iflags.debug_prevent_pline = (boolean) val;
1501.     }
1502. 
1503.     return 0;
1504. }
1505. 
1506. /* flip level */
1507. /* nh.flip_level(n); */
1508. staticfn int
1509. nhl_flip_level(lua_State *L)
1510. {
1511.     int argc = lua_gettop(L);
1512.     int flp = 0;
1513. 
1514.     if (argc == 1)
1515.         flp = lua_tointeger(L, 1);
1516. 
1517.     flip_level(flp, !gi.in_mklev);
1518. 
1519.     return 0;
1520. }
1521. 
1522. DISABLE_WARNING_UNREACHABLE_CODE
1523. 
1524. /* does location at x,y have timer? */
1525. /* local has_melttimer = nh.has_timer_at(x,y, "melt-ice"); */
1526. /* local has_melttimer = nh.has_timer_at({x=4,y=7}, "melt-ice"); */
1527. staticfn int
1528. nhl_timer_has_at(lua_State *L)
1529. {
1530.     boolean ret = FALSE;
1531.     short timertype = nhl_get_timertype(L, -1);
1532.     lua_Integer lx, ly;
1533.     coordxy x, y;
1534.     long when;
1535. 
1536.     lua_pop(L, 1); /* remove timertype */
1537.     if (!nhl_get_xy_params(L, &lx, &ly)) {
1538.         nhl_error(L, "nhl_timer_has_at: Wrong args");
1539.         /*NOTREACHED*/
1540.         return 0;
1541.     }
1542. 
1543.     x = (coordxy) lx;
1544.     y = (coordxy) ly;
1545.     cvt_to_abscoord(&x, &y);
1546. 
1547.     if (isok(x, y)) {
1548.         when = spot_time_expires(x, y, timertype);
1549.         ret = (when > 0L);
1550.     }
1551.     lua_pushboolean(L, ret);
1552.     return 1;
1553. }
1554. 
1555. /* when does location at x,y timer trigger? */
1556. /* local melttime = nh.peek_timer_at(x,y, "melt-ice"); */
1557. /* local melttime = nh.peek_timer_at({x=5,y=6}, "melt-ice"); */
1558. staticfn int
1559. nhl_timer_peek_at(lua_State *L)
1560. {
1561.     long when = 0L;
1562.     short timertype = nhl_get_timertype(L, -1);
1563.     lua_Integer lx, ly;
1564.     coordxy x, y;
1565. 
1566.     lua_pop(L, 1); /* remove timertype */
1567.     if (!nhl_get_xy_params(L, &lx, &ly)) {
1568.         nhl_error(L, "nhl_timer_peek_at: Wrong args");
1569.         /*NOTREACHED*/
1570.         return 0;
1571.     }
1572. 
1573.     x = (coordxy) lx;
1574.     y = (coordxy) ly;
1575.     cvt_to_abscoord(&x, &y);
1576. 
1577.     if (timer_is_pos(timertype) && isok(x, y))
1578.         when = spot_time_expires(x, y, timertype);
1579.     lua_pushinteger(L, when);
1580.     return 1;
1581. }
1582. 
1583. /* stop timer at location x,y */
1584. /* nh.stop_timer_at(x,y, "melt-ice"); */
1585. /* nh.stop_timer_at({x=6,y=8}, "melt-ice"); */
1586. staticfn int
1587. nhl_timer_stop_at(lua_State *L)
1588. {
1589.     short timertype = nhl_get_timertype(L, -1);
1590.     lua_Integer lx, ly;
1591.     coordxy x, y;
1592. 
1593.     lua_pop(L, 1); /* remove timertype */
1594.     if (!nhl_get_xy_params(L, &lx, &ly)) {
1595.         nhl_error(L, "nhl_timer_stop_at: Wrong args");
1596.         /*NOTREACHED*/
1597.         return 0;
1598.     }
1599. 
1600.     x = (coordxy) lx;
1601.     y = (coordxy) ly;
1602.     cvt_to_abscoord(&x, &y);
1603. 
1604.     if (timer_is_pos(timertype) && isok(x, y))
1605.         spot_stop_timers(x, y, timertype);
1606.     return 0;
1607. }
1608. 
1609. /* start timer at location x,y */
1610. /* nh.start_timer_at(x,y, "melt-ice", 10); */
1611. staticfn int
1612. nhl_timer_start_at(lua_State *L)
1613. {
1614.     short timertype = nhl_get_timertype(L, -2);
1615.     long when = lua_tointeger(L, -1);
1616.     lua_Integer lx, ly;
1617.     coordxy x, y;
1618. 
1619.     lua_pop(L, 2); /* remove when and timertype */
1620.     if (!nhl_get_xy_params(L, &lx, &ly)) {
1621.         nhl_error(L, "nhl_timer_start_at: Wrong args");
1622.         /*NOTREACHED*/
1623.         return 0;
1624.     }
1625. 
1626.     x = (coordxy) lx;
1627.     y = (coordxy) ly;
1628.     cvt_to_abscoord(&x, &y);
1629. 
1630.     if (timer_is_pos(timertype) && isok(x, y)) {
1631.         long where = ((long) x << 16) | (long) y;
1632. 
1633.         spot_stop_timers(x, y, timertype);
1634.         (void) start_timer((long) when, TIMER_LEVEL, MELT_ICE_AWAY,
1635.                            long_to_any(where));
1636.     }
1637.     return 0;
1638. }
1639. 
1640. /* returns the visual interpretation of the key bound to an extended command,
1641.    or the ext cmd name if not bound to any key */
1642. /* local helpkey = eckey("help"); */
1643. staticfn int
1644. nhl_get_cmd_key(lua_State *L)
1645. {
1646.     int argc = lua_gettop(L);
1647. 
1648.     if (argc == 1) {
1649.         const char *cmd = luaL_checkstring(L, 1);
1650.         char *key = cmd_from_ecname(cmd);
1651. 
1652.         lua_pushstring(L, key);
1653.         return 1;
1654.     }
1655. 
1656.     return 0;
1657. }
1658. 
1659. /* add or remove a lua function callback */
1660. /* callback("level_enter", "function_name"); */
1661. /* callback("level_enter", "function_name", true); */
1662. /* level_enter, level_leave, cmd_before */
1663. staticfn int
1664. nhl_callback(lua_State *L)
1665. {
1666.     int argc = lua_gettop(L);
1667.     int i;
1668.     boolean rm;
1669.     const char *fn, *cb;
1670. 
1671.     if (!gl.luacore) {
1672.         panic("nh luacore not inited");
1673.         /*NOTREACHED*/
1674.         return 0;
1675.     }
1676.     if (argc == 2 || argc == 3) {
1677.         if (argc == 2) {
1678.             rm = FALSE;
1679.             fn = luaL_checkstring(L, -1);
1680.             cb = luaL_checkstring(L, -2);
1681.         } else {
1682.             rm = lua_toboolean(L, -1);
1683.             fn = luaL_checkstring(L, -2);
1684.             cb = luaL_checkstring(L, -3);
1685.         }
1686.         for (i = 0; i < NUM_NHCB; i++)
1687.             if (!strcmp(cb, nhcb_name[i]))
1688.                 break;
1689.         if (i >= NUM_NHCB)
1690.             return 0;
1691. 
1692.         if (rm) {
1693.             nhcb_counts[i]--;
1694.             if (nhcb_counts[i] < 0)
1695.                 impossible("nh.callback counts are wrong");
1696.         } else {
1697.             nhcb_counts[i]++;
1698.         }
1699. 
1700.         lua_getglobal(gl.luacore, rm ? "nh_callback_rm" : "nh_callback_set");
1701.         lua_pushstring(gl.luacore, cb);
1702.         lua_pushstring(gl.luacore, fn);
1703.         nhl_pcall_handle(gl.luacore, 2, 0, "nhl_callback", NHLpa_panic);
1704.     }
1705.     return 0;
1706. }
1707. 
1708. /* store or restore game state */
1709. /*
1710.  * Currently handles
1711.  *   turn counter,
1712.  *   hero inventory and hunger,
1713.  *   hero attributes and skills and conducts (all via 'struct u'),
1714.  *   object discoveries,
1715.  *   monster generation and vanquished statistics.
1716.  * NOTE: wouldn't work after restore if game has been saved, so the
1717.  * #save command ('S') is disabled during the tutorial.
1718.  */
1719. /* gamestate(); -- save state */
1720. /* gamestate(true); -- restore state */
1721. staticfn int
1722. nhl_gamestate(lua_State *L)
1723. {
1724.     long wornmask;
1725.     struct obj *otmp;
1726.     int argc = lua_gettop(L);
1727.     boolean reststate = (argc > 0) ? lua_toboolean(L, -1) : FALSE;
1728.     int otyp;
1729. 
1730.     debugpline4("gamestate: %d:%d (%c vs %c)", u.uz.dnum, u.uz.dlevel,
1731.                 reststate ? 'T' : 'F', gg.gmst_stored ? 't' : 'f');
1732. 
1733.     if (reststate && gg.gmst_stored) {
1734.         d_level cur_uz = u.uz, cur_uz0 = u.uz0;
1735. 
1736.         /* restore game state */
1737.         svm.moves = gg.gmst_moves;
1738.         pline("Resetting time to move #%ld.", svm.moves);
1739.         gg.gmst_moves = 0L;
1740. 
1741.         gl.lastinvnr = 51;
1742.         while (gi.invent)
1743.             useupall(gi.invent);
1744.         while ((otmp = gg.gmst_invent) != NULL) {
1745.             wornmask = otmp->owornmask;
1746.             otmp->owornmask = 0L;
1747.             extract_nobj(otmp, &gg.gmst_invent);
1748.             addinv_nomerge(otmp);
1749.             if (wornmask)
1750.                 setworn(otmp, wornmask);
1751.         }
1752.         assert(gg.gmst_ubak != NULL);
1753.         (void) memcpy((genericptr_t) &u, gg.gmst_ubak, sizeof u);
1754.         assert(gg.gmst_disco != NULL);
1755.         (void) memcpy((genericptr_t) &svd.disco, gg.gmst_disco,
1756.                       sizeof svd.disco);
1757.         assert(gg.gmst_mvitals != NULL);
1758.         (void) memcpy((genericptr_t) &svm.mvitals, gg.gmst_mvitals,
1759.                       sizeof svm.mvitals);
1760.         /* clear user-given object type names */
1761.         for (otyp = 0; otyp < NUM_OBJECTS; otyp++)
1762.             if (objects[otyp].oc_uname) {
1763.                 free(objects[otyp].oc_uname);
1764.                 objects[otyp].oc_uname = (char *) 0;
1765.             }
1766.         /* some restored state would confuse the level change in progress */
1767.         u.uz = cur_uz, u.uz0 = cur_uz0;
1768.         init_uhunger();
1769.         free_tutorial(); /* release gg.gmst_XYZ */
1770.         gg.gmst_stored = FALSE;
1771.         (void) memcpy(svs.spl_book, gg.gmst_spl_book, sizeof svs.spl_book);
1772.     } else if (!reststate && !gg.gmst_stored) {
1773.         /* store game state */
1774.         gg.gmst_moves = svm.moves;
1775.         while ((otmp = gi.invent) != NULL) {
1776.             wornmask = otmp->owornmask;
1777.             setnotworn(otmp);
1778.             freeinv(otmp);
1779.             otmp->owornmask = wornmask; /* flag for later restore */
1780.             otmp->nobj = gg.gmst_invent;
1781.             gg.gmst_invent = otmp;
1782.         }
1783.         gl.lastinvnr = 51; /* next inv letter to try to use will be 'a' */
1784.         gg.gmst_ubak = (genericptr_t) alloc(sizeof u);
1785.         (void) memcpy(gg.gmst_ubak, (genericptr_t) &u, sizeof u);
1786.         gg.gmst_disco = (genericptr_t) alloc(sizeof svd.disco);
1787.         (void) memcpy(gg.gmst_disco, (genericptr_t) &svd.disco,
1788.                       sizeof svd.disco);
1789.         gg.gmst_mvitals = (genericptr_t) alloc(sizeof svm.mvitals);
1790.         (void) memcpy(gg.gmst_mvitals, (genericptr_t) &svm.mvitals,
1791.                       sizeof svm.mvitals);
1792.         (void) memcpy(gg.gmst_spl_book, svs.spl_book, sizeof svs.spl_book);
1793.         (void) memset(svs.spl_book, 0, sizeof(svs.spl_book));
1794.         gg.gmst_stored = TRUE;
1795.     } else {
1796.         impossible("nhl_gamestate: inconsistent state (%s vs %s)",
1797.                    reststate ? "restore" : "save",
1798.                    gg.gmst_stored ? "already stored" : "not stored");
1799.     }
1800.     update_inventory();
1801.     return 0;
1802. }
1803. 
1804. RESTORE_WARNING_UNREACHABLE_CODE
1805. 
1806. /* free dynamic date allocated when entering tutorial;
1807.    called when exiting tutorial normally or if player quits while in it */
1808. void
1809. free_tutorial(void)
1810. {
1811.     struct obj *otmp;
1812. 
1813.     /* for normal tutorial exit, gmst_invent will already be Null */
1814.     while ((otmp = gg.gmst_invent) != 0) {
1815.         /* set otmp->where = OBJ_FREE, otmp->nobj = NULL */
1816.         extract_nobj(otmp, &gg.gmst_invent);
1817.         /* gmst_invent is a list of invent items sequestered when entering
1818.            the tutorial; for them, owornmask is used as a flag to re-wear
1819.            them when exiting tutorial, not that they are currently worn;
1820.            clear it to avoid a "deleting worn obj" complaint from obfree() */
1821.         otmp->owornmask = 0L;
1822.         /* dealloc_obj() isn't enough (for containers, it assumes that
1823.            caller has already freed their contents) */
1824.         obfree(otmp, (struct obj *) 0);
1825.     }
1826. 
1827.     if (gg.gmst_ubak)
1828.         free(gg.gmst_ubak), gg.gmst_ubak = NULL;
1829.     if (gg.gmst_disco)
1830.         free(gg.gmst_disco), gg.gmst_disco = NULL;
1831.     if (gg.gmst_mvitals)
1832.         free(gg.gmst_mvitals), gg.gmst_mvitals = NULL;
1833. }
1834. 
1835. /* called from gotolevel(do.c) */
1836. void
1837. tutorial(boolean entering)
1838. {
1839.     l_nhcore_call(entering ? NHCORE_ENTER_TUTORIAL : NHCORE_LEAVE_TUTORIAL);
1840. 
1841.     if (!entering) { /* after leaving, can't go back */
1842.         nhcore_call_available[NHCORE_ENTER_TUTORIAL]
1843.             = nhcore_call_available[NHCORE_LEAVE_TUTORIAL]
1844.                 = FALSE;
1845.     }
1846. }
1847. 
1848. static const struct luaL_Reg nhl_functions[] = {
1849.     { "test", nhl_test },
1850. 
1851.     { "getmap", nhl_getmap },
1852. #if 0
1853.     { "setmap", nhl_setmap },
1854. #endif
1855.     { "gettrap", nhl_gettrap },
1856.     { "deltrap", nhl_deltrap },
1857. 
1858.     { "has_timer_at", nhl_timer_has_at },
1859.     { "peek_timer_at", nhl_timer_peek_at },
1860.     { "stop_timer_at", nhl_timer_stop_at },
1861.     { "start_timer_at", nhl_timer_start_at },
1862. 
1863.     { "abscoord", nhl_abs_coord },
1864. 
1865.     { "impossible", nhl_impossible },
1866.     { "pline", nhl_pline },
1867.     { "verbalize", nhl_verbalize },
1868.     { "menu", nhl_menu },
1869.     { "text", nhl_text },
1870.     { "getlin", nhl_getlin },
1871.     { "eckey", nhl_get_cmd_key },
1872.     { "callback", nhl_callback },
1873.     { "gamestate", nhl_gamestate },
1874. 
1875.     { "makeplural", nhl_makeplural },
1876.     { "makesingular", nhl_makesingular },
1877.     { "s_suffix", nhl_s_suffix },
1878.     { "ing_suffix", nhl_ing_suffix },
1879.     { "an", nhl_an },
1880.     { "rn2", nhl_rn2 },
1881.     { "random", nhl_random },
1882.     { "level_difficulty", nhl_level_difficulty },
1883.     { "is_genocided", nhl_is_genocided },
1884.     { "debug_themerm", nhl_get_debug_themerm_name },
1885.     { "parse_config", nhl_parse_config },
1886.     { "get_config", nhl_get_config },
1887.     { "get_config_errors", l_get_config_errors },
1888. #ifdef DUMPLOG
1889.     { "dump_fmtstr", nhl_dump_fmtstr },
1890. #endif /* DUMPLOG */
1891.     { "dnum_name", nhl_dnum_name },
1892.     { "int_to_pmname", nhl_int_to_pm_name },
1893.     { "int_to_objname", nhl_int_to_obj_name },
1894.     { "variable", nhl_variable },
1895.     { "stairways", nhl_stairways },
1896.     { "pushkey", nhl_pushkey },
1897.     { "doturn", nhl_doturn },
1898.     { "debug_flags", nhl_debug_flags },
1899.     { "flip_level", nhl_flip_level },
1900.     { NULL, NULL }
1901. };
1902. 
1903. static const struct {
1904.     const char *name;
1905.     long value;
1906. } nhl_consts[] = {
1907.     { "COLNO",  COLNO },
1908.     { "ROWNO",  ROWNO },
1909.     { "NUMMONS", NUMMONS },
1910.     { "LOW_PM", LOW_PM },
1911.     { "HIGH_PM", HIGH_PM },
1912.     { "FIRST_OBJECT", FIRST_OBJECT },
1913.     { "LAST_OBJECT", NUM_OBJECTS-1 },
1914. #ifdef DLB
1915.     { "DLB", 1 },
1916. #else
1917.     { "DLB", 0 },
1918. #endif /* DLB */
1919.     { NULL, 0 },
1920. };
1921. 
1922. /* register and init the constants table */
1923. staticfn void
1924. init_nhc_data(lua_State *L)
1925. {
1926.     int i;
1927. 
1928.     lua_newtable(L);
1929. 
1930.     for (i = 0; nhl_consts[i].name; i++) {
1931.         lua_pushstring(L, nhl_consts[i].name);
1932.         lua_pushinteger(L, nhl_consts[i].value);
1933.         lua_rawset(L, -3);
1934.     }
1935. 
1936.     lua_setglobal(L, "nhc");
1937. }
1938. 
1939. staticfn int
1940. nhl_push_anything(lua_State *L, int anytype, void *src)
1941. {
1942.     anything any = cg.zeroany;
1943. 
1944.     switch (anytype) {
1945.     case ANY_INT:
1946.         any.a_int = *(int *) src;
1947.         lua_pushinteger(L, any.a_int);
1948.         break;
1949.     case ANY_UCHAR:
1950.         any.a_uchar = *(uchar *) src;
1951.         lua_pushinteger(L, any.a_uchar);
1952.         break;
1953.     case ANY_SCHAR:
1954.         any.a_schar = *(schar *) src;
1955.         lua_pushinteger(L, any.a_schar);
1956.         break;
1957.     }
1958.     return 1;
1959. }
1960. 
1961. DISABLE_WARNING_UNREACHABLE_CODE
1962. 
1963. staticfn int
1964. nhl_meta_u_index(lua_State *L)
1965. {
1966.     static const struct {
1967.         const char *name;
1968.         void *ptr;
1969.         int type;
1970.     } ustruct[] = {
1971.         { "ux", &(u.ux), ANY_UCHAR },
1972.         { "uy", &(u.uy), ANY_UCHAR },
1973.         { "dx", &(u.dx), ANY_SCHAR },
1974.         { "dy", &(u.dy), ANY_SCHAR },
1975.         { "dz", &(u.dz), ANY_SCHAR },
1976.         { "tx", &(u.tx), ANY_UCHAR },
1977.         { "ty", &(u.ty), ANY_UCHAR },
1978.         { "ulevel", &(u.ulevel), ANY_INT },
1979.         { "ulevelmax", &(u.ulevelmax), ANY_INT },
1980.         { "uhunger", &(u.uhunger), ANY_INT },
1981.         { "nv_range", &(u.nv_range), ANY_INT },
1982.         { "xray_range", &(u.xray_range), ANY_INT },
1983.         { "umonster", &(u.umonster), ANY_INT },
1984.         { "umonnum", &(u.umonnum), ANY_INT },
1985.         { "mh", &(u.mh), ANY_INT },
1986.         { "mhmax", &(u.mhmax), ANY_INT },
1987.         { "mtimedone", &(u.mtimedone), ANY_INT },
1988.         { "dlevel", &(u.uz.dlevel), ANY_SCHAR }, /* actually coordxy */
1989.         { "dnum", &(u.uz.dnum), ANY_SCHAR },     /* actually coordxy */
1990.         { "uluck", &(u.uluck), ANY_SCHAR },
1991.         { "uhp", &(u.uhp), ANY_INT },
1992.         { "uhpmax", &(u.uhpmax), ANY_INT },
1993.         { "uen", &(u.uen), ANY_INT },
1994.         { "uenmax", &(u.uenmax), ANY_INT },
1995.     };
1996.     const char *tkey = luaL_checkstring(L, 2);
1997.     int i;
1998. 
1999.     /* FIXME: doesn't really work, eg. negative values for u.dx */
2000.     for (i = 0; i < SIZE(ustruct); i++)
2001.         if (!strcmp(tkey, ustruct[i].name)) {
2002.             return nhl_push_anything(L, ustruct[i].type, ustruct[i].ptr);
2003.         }
2004. 
2005.     if (!strcmp(tkey, "inventory")) {
2006.         nhl_push_obj(L, gi.invent);
2007.         return 1;
2008.     } else if (!strcmp(tkey, "role")) {
2009.         lua_pushstring(L, gu.urole.name.m);
2010.         return 1;
2011.     } else if (!strcmp(tkey, "moves")) {
2012.         lua_pushinteger(L, svm.moves);
2013.         return 1;
2014.     } else if (!strcmp(tkey, "uhave_amulet")) {
2015.         lua_pushinteger(L, u.uhave.amulet);
2016.         return 1;
2017.     } else if (!strcmp(tkey, "depth")) {
2018.         lua_pushinteger(L, depth(&u.uz));
2019.         return 1;
2020.     } else if (!strcmp(tkey, "invocation_level")) {
2021.         lua_pushboolean(L, Invocation_lev(&u.uz));
2022.         return 1;
2023.     }
2024. 
2025.     nhl_error(L, "Unknown u table index");
2026.     /*NOTREACHED*/
2027.     return 0;
2028. }
2029. 
2030. staticfn int
2031. nhl_meta_u_newindex(lua_State *L)
2032. {
2033.     nhl_error(L, "Cannot set u table values");
2034.     /*NOTREACHED*/
2035.     return 0;
2036. }
2037. 
2038. RESTORE_WARNING_UNREACHABLE_CODE
2039. 
2040. staticfn int
2041. nhl_u_clear_inventory(lua_State *L UNUSED)
2042. {
2043.     while (gi.invent)
2044.         useupall(gi.invent);
2045.     return 0;
2046. }
2047. 
2048. /* Put object into player's inventory */
2049. /* u.giveobj(obj.new("rock")); */
2050. staticfn int
2051. nhl_u_giveobj(lua_State *L)
2052. {
2053.     return nhl_obj_u_giveobj(L);
2054. }
2055. 
2056. static const struct luaL_Reg nhl_u_functions[] = {
2057.     { "clear_inventory", nhl_u_clear_inventory },
2058.     { "giveobj", nhl_u_giveobj },
2059.     { NULL, NULL }
2060. };
2061. 
2062. staticfn void
2063. init_u_data(lua_State *L)
2064. {
2065.     lua_newtable(L);
2066.     luaL_setfuncs(L, nhl_u_functions, 0);
2067.     lua_newtable(L);
2068.     lua_pushcfunction(L, nhl_meta_u_index);
2069.     lua_setfield(L, -2, "__index");
2070.     lua_pushcfunction(L, nhl_meta_u_newindex);
2071.     lua_setfield(L, -2, "__newindex");
2072.     lua_setmetatable(L, -2);
2073.     lua_setglobal(L, "u");
2074. }
2075. 
2076. #ifdef notyet
2077. staticfn int
2078. nhl_set_package_path(lua_State *L, const char *path)
2079. {
2080.     if (LUA_TTABLE != lua_getglobal(L, "package")) {
2081.         impossible("package not a table in nhl_set_package_path");
2082.         return 1;
2083.     };
2084.     lua_pushstring(L, path);
2085.     lua_setfield(L, -2, "path");
2086.     lua_pop(L, 1);
2087.     return 0;
2088. }
2089. #endif
2090. 
2091. staticfn int
2092. traceback_handler(lua_State *L)
2093. {
2094.     luaL_traceback(L, L, lua_tostring(L, 1), 0);
2095.     /* TODO: call impossible() if fuzzing? */
2096.     return 1;
2097. }
2098. 
2099. staticfn uint32_t
2100. nhl_getmeminuse(lua_State *L)
2101. {
2102.     return lua_gc(L, LUA_GCCOUNT) * 1024 + lua_gc(L, LUA_GCCOUNTB);
2103. }
2104. 
2105. /* lua_pcall with our traceback handler and memory and instruction step
2106.  * limiting.
2107.  *  On error, traceback will be on top of stack */
2108. int
2109. nhl_pcall(lua_State *L, int nargs, int nresults, const char *name)
2110. {
2111.     struct nhl_user_data *nud;
2112.     int rv;
2113. 
2114.     lua_pushcfunction(L, traceback_handler);
2115.     lua_insert(L, 1);
2116.     (void) lua_getallocf(L, (void **) &nud);
2117. #ifdef NHL_SANDBOX
2118.     if (nud && name) {
2119.         nud->name = name;
2120.     }
2121.     /* NB: We don't need to deal with nud->memlimit - Lua handles that. */
2122.     if (nud && (nud->steps || nud->perpcall)) {
2123.         if (nud->perpcall) {
2124.             nud->steps = nud->perpcall;
2125.             nud->statctr = 0;
2126.         }
2127.         if (setjmp(nud->jb)) {
2128.             /* panic, because we don't know if the game state is corrupt */
2129.             /* XXX can we get a lua stack trace as well? */
2130.             panic("Lua time exceeded %d:%s", nud->sid,
2131.                   nud->name ? nud->name : "(unknown)");
2132.         }
2133.     }
2134. #endif
2135. 
2136.     rv = lua_pcall(L, nargs, nresults, 1);
2137. 
2138.     lua_remove(L, 1); /* remove handler */
2139. 
2140. #ifdef NHL_SANDBOX
2141.     if (nud && nud->perpcall && gl.loglua) {
2142.         long ic = nud->statctr * NHL_SB_STEPSIZE; // an approximation
2143.         livelog_printf(LL_DEBUG, "LUASTATS PCAL %d:%s %ld", nud->sid,
2144.                        nud->name, ic);
2145.     }
2146.     if (nud && nud->memlimit && gl.loglua) {
2147.         livelog_printf(LL_DEBUG, "LUASTATS PMEM %d:%s %lu", nud->sid,
2148.                        nud->name, (long unsigned) nhl_getmeminuse(L));
2149.     }
2150. #endif
2151.     return rv;
2152. }
2153. 
2154. int
2155. nhl_pcall_handle(lua_State *L, int nargs, int nresults, const char *name,
2156.                  NHL_pcall_action npa)
2157. {
2158.     int rv = nhl_pcall(L, nargs, nresults, name);
2159.     if (rv) {
2160.         nhl_user_data *nud;
2161.         (void) lua_getallocf(L, (void **) &nud);
2162.         /* XXX can we get a lua stack trace as well? */
2163.         switch (npa) {
2164.         case NHLpa_panic:
2165.             panic("Lua error %d:%s %s", nud->sid,
2166.                   nud->name ? nud->name : "(unknown)", lua_tostring(L, -1));
2167.             /*NOTREACHED*/
2168.             break;
2169.         case NHLpa_impossible:
2170.             impossible("Lua error: %d:%s %s", nud->sid,
2171.                        nud->name ? nud->name : "(unknown)",
2172.                        lua_tostring(L, -1));
2173.                 /* Drop the error.  If the caller cares, use nhl_pcall(). */
2174.             lua_pop(L, 1);
2175.         }
2176.     }
2177.     return rv;
2178. }
2179. 
2180. /* XXX impossible() should be swappable with pline/nothing/panic via flag */
2181. /* read lua code/data from a dlb module or an external file
2182.    into a string buffer and feed that to lua */
2183. boolean
2184. nhl_loadlua(lua_State *L, const char *fname)
2185. {
2186. #define LOADCHUNKSIZE (1L << 13) /* 8K */
2187.     boolean ret = TRUE;
2188.     dlb *fh;
2189.     char *buf = (char *) 0, *bufin, *bufout, *p, *nl, *altfname;
2190.     long buflen, ct, cnt;
2191.     int llret;
2192. 
2193.     altfname = (char *) alloc(Strlen(fname) + 3); /* 3: '('...')\0' */
2194.     /* don't know whether 'fname' is inside a dlb container;
2195.        if we did, we could choose between "nhdat(<fname>)" and "<fname>"
2196.        but since we don't, compromise */
2197.     Sprintf(altfname, "(%s)", fname);
2198.     fh = dlb_fopen(fname, RDBMODE);
2199.     if (!fh) {
2200.         impossible("nhl_loadlua: Error opening %s", altfname);
2201.         ret = FALSE;
2202.         goto give_up;
2203.     }
2204. 
2205.     dlb_fseek(fh, 0L, SEEK_END);
2206.     buflen = dlb_ftell(fh);
2207.     dlb_fseek(fh, 0L, SEEK_SET);
2208. 
2209.     /* extra +1: room to add final '\n' if missing */
2210.     buf = bufout = (char *) alloc(FITSint(buflen + 1 + 1));
2211.     buf[0] = '\0';
2212.     bufin = bufout = buf;
2213. 
2214.     ct = 0L;
2215.     while (buflen > 0 || ct) {
2216.         /*
2217.          * Semi-arbitrarily limit reads to 8K at a time.  That's big
2218.          * enough to cover the majority of our Lua files in one bite
2219.          * but small enough to fully exercise the partial record
2220.          * handling (when processing the castle's level description).
2221.          *
2222.          * [For an external file (non-DLB), VMS may only be able to
2223.          * read at most 32K-1 at a time depending on the file format
2224.          * in use, and fseek(SEEK_END) only yields an upper bound on
2225.          * the actual amount of data in that situation.]
2226.          */
2227.         if ((cnt = dlb_fread(bufin, 1, min((int) buflen, LOADCHUNKSIZE), fh))
2228.             < 0L)
2229.             break;
2230.         buflen -= cnt; /* set up for next iteration, if any */
2231.         if (cnt == 0L) {
2232.             *bufin = '\n'; /* very last line is unterminated? */
2233.             cnt = 1;
2234.         }
2235.         bufin[cnt] = '\0'; /* fread() doesn't do this */
2236. 
2237.         /* in case partial line was leftover from previous fread */
2238.         bufin -= ct, cnt += ct, ct = 0;
2239. 
2240.         while (cnt > 0) {
2241.             if ((nl = strchr(bufin, '\n')) != 0) {
2242.                 /* normal case, newline is present */
2243.                 ct = (long) (nl - bufin + 1L); /* +1: keep the newline */
2244.                 for (p = bufin; p <= nl; ++p)
2245.                     *bufout++ = *bufin++;
2246.                 if (*bufin == '\r')
2247.                     ++bufin, ++ct;
2248.                 /* update for next loop iteration */
2249.                 cnt -= ct;
2250.                 ct = 0;
2251.             } else if (strlen(bufin) < LOADCHUNKSIZE) {
2252.                 /* no newline => partial record; move unprocessed chars
2253.                    to front of input buffer (bufin portion of buf[]) */
2254.                 ct = cnt = (long) (eos(bufin) - bufin);
2255.                 for (p = bufout; cnt > 0; --cnt)
2256.                     *p++ = *bufin++;
2257.                 *p = '\0';
2258.                 bufin = p; /* next fread() populates buf[] starting here */
2259.                 /* cnt==0 so inner loop will terminate */
2260.             } else {
2261.                 /* LOADCHUNKSIZE portion of buffer already completely full */
2262.                 impossible("(%s) line too long", altfname);
2263.                 goto give_up;
2264.             }
2265.         }
2266.     }
2267.     *bufout = '\0';
2268.     (void) dlb_fclose(fh);
2269. 
2270.     llret = luaL_loadbuffer(L, buf, strlen(buf), altfname);
2271.     if (llret != LUA_OK) {
2272.         impossible("luaL_loadbuffer: Error loading %s: %s", altfname,
2273.                    lua_tostring(L, -1));
2274.         ret = FALSE;
2275.         goto give_up;
2276.     } else {
2277.         if (nhl_pcall_handle(L, 0, LUA_MULTRET, fname, NHLpa_impossible)) {
2278.             ret = FALSE;
2279.             goto give_up;
2280.         }
2281.     }
2282. 
2283.  give_up:
2284.     if (altfname)
2285.         free((genericptr_t) altfname);
2286.     if (buf)
2287.         free((genericptr_t) buf);
2288.     return ret;
2289. #undef LOADCHUNKSIZE
2290. }
2291. 
2292. DISABLE_WARNING_CONDEXPR_IS_CONSTANT
2293. 
2294. lua_State *
2295. nhl_init(nhl_sandbox_info *sbi)
2296. {
2297.     /* It would be nice to import EXPECTED from each build system. XXX */
2298.     /* And it would be nice to do it only once, but it's cheap. */
2299. #ifndef NHL_VERSION_EXPECTED
2300. #if LUA_VERSION_NUM >= 505
2301. #define NHL_VERSION_EXPECTED 50500
2302. #else
2303. #define NHL_VERSION_EXPECTED 50408
2304. #endif
2305. #endif
2306. 
2307. #ifdef NHL_SANDBOX
2308.     if (NHL_VERSION_EXPECTED != LUA_VERSION_RELEASE_NUM) {
2309.         panic(
2310.             "sandbox doesn't know this Lua version: this=%d != expected=%d ",
2311.             LUA_VERSION_RELEASE_NUM, NHL_VERSION_EXPECTED);
2312.     }
2313. #endif
2314. 
2315.     lua_State *L = nhlL_newstate(sbi, "nhl_init");
2316.     if(!L) return 0;
2317. 
2318.     iflags.in_lua = TRUE;
2319.     /* Temporary for development XXX */
2320.     /* Turn this off in config.h to disable the sandbox. */
2321. #ifdef NHL_SANDBOX
2322.     nhlL_openlibs(L, sbi->flags);
2323. #else
2324.     luaL_openlibs(L);
2325. #endif
2326. 
2327. #ifdef notyet
2328.     if (sbi->flags & NHL_SB_PACKAGE) {
2329.         /* XXX Is this still needed? */
2330.         if (nhl_set_package_path(L, "./?.lua"))
2331.             return 0;
2332.     }
2333. #endif
2334. 
2335.     /* register nh -table, and functions for it */
2336.     lua_newtable(L);
2337.     luaL_setfuncs(L, nhl_functions, 0);
2338.     lua_setglobal(L, "nh");
2339. 
2340.     /* init nhc -table */
2341.     init_nhc_data(L);
2342. 
2343.     /* init u -table */
2344.     init_u_data(L);
2345. 
2346.     l_selection_register(L);
2347.     l_register_des(L);
2348. 
2349.     l_obj_register(L);
2350. 
2351.     /* nhlib.lua assumes the math table exists. */
2352.     if (LUA_TTABLE != lua_getglobal(L, "math")) {
2353.         lua_newtable(L);
2354.         lua_setglobal(L, "math");
2355.     }
2356. 
2357.     if (!nhl_loadlua(L, "nhlib.lua")) {
2358.         nhl_done(L);
2359.         return (lua_State *) 0;
2360.     }
2361. 
2362.     return L;
2363. }
2364. 
2365. RESTORE_WARNING_CONDEXPR_IS_CONSTANT
2366. 
2367. void
2368. nhl_done(lua_State *L)
2369. {
2370.     if (L) {
2371.         nhl_user_data *nud = 0;
2372.         (void) lua_getallocf(L, (void **) &nud);
2373.         if (gl.loglua) {
2374.             if (nud && nud->osteps) {
2375.                 long ic = nud->statctr * NHL_SB_STEPSIZE; // an approximation
2376.                 livelog_printf(LL_DEBUG, "LUASTATS DONE %d:%s %ld", nud->sid,
2377.                                nud->name, ic);
2378.             }
2379.             if (nud && nud->memlimit && !nud->perpcall) {
2380.                 livelog_printf(LL_DEBUG, "LUASTATS DMEM %d:%s %lu", nud->sid,
2381.                                nud->name, (long unsigned) nhl_getmeminuse(L));
2382.             }
2383.         }
2384.         lua_close(L);
2385.         if (nud)
2386.             nhl_alloc(NULL, nud, 0, 0); // free nud
2387.     }
2388.     iflags.in_lua = FALSE;
2389. }
2390. 
2391. boolean
2392. load_lua(const char *name, nhl_sandbox_info *sbi)
2393. {
2394.     boolean ret = TRUE;
2395.     lua_State *L = nhl_init(sbi);
2396. 
2397.     if (!L) {
2398.         ret = FALSE;
2399.         goto give_up;
2400.     }
2401. 
2402.     if (!nhl_loadlua(L, name)) {
2403.         ret = FALSE;
2404.         goto give_up;
2405.     }
2406. 
2407.  give_up:
2408.     nhl_done(L);
2409. 
2410.     return ret;
2411. }
2412. 
2413. DISABLE_WARNING_CONDEXPR_IS_CONSTANT
2414. 
2415. const char *
2416. get_lua_version(void)
2417. {
2418.     nhl_sandbox_info sbi = { NHL_SB_VERSION, 1 * 1024 * 1024, 0,
2419.                              1 * 1024 * 1024 };
2420. 
2421.     if (gl.lua_ver[0] == 0) {
2422.         lua_State *L = nhl_init(&sbi);
2423. 
2424.         if (L) {
2425.             size_t len = 0;
2426.             const char *vs = (const char *) 0;
2427. 
2428.             /* LUA_VERSION yields "<major>.<minor>" although we check to see
2429.                whether it is "Lua-<major>.<minor>" and strip prefix if so;
2430.                LUA_RELEASE is <LUA_VERSION>.<LUA_VERSION_RELEASE> but doesn't
2431.                get set up as a lua global */
2432.             lua_getglobal(L, "_RELEASE");
2433.             if (lua_isstring(L, -1))
2434.                 vs = lua_tolstring(L, -1, &len);
2435. #ifdef LUA_RELEASE
2436.             else
2437.                 vs = LUA_RELEASE, len = strlen(vs);
2438. #endif
2439.             if (!vs) {
2440.                 lua_getglobal(L, "_VERSION");
2441.                 if (lua_isstring(L, -1))
2442.                     vs = lua_tolstring(L, -1, &len);
2443. #ifdef LUA_VERSION
2444.                 else
2445.                     vs = LUA_VERSION, len = strlen(vs);
2446. #endif
2447.             }
2448.             if (vs && len < sizeof gl.lua_ver) {
2449.                 if (!strncmpi(vs, "Lua", 3)) {
2450.                     vs += 3;
2451.                     if (*vs == '-' || *vs == ' ')
2452.                         vs += 1;
2453.                 }
2454.                 Strcpy(gl.lua_ver, vs);
2455.             }
2456.         }
2457.         nhl_done(L);
2458. #ifdef LUA_COPYRIGHT
2459.         if (sizeof LUA_COPYRIGHT <= sizeof gl.lua_copyright)
2460.             Strcpy(gl.lua_copyright, LUA_COPYRIGHT);
2461. #endif
2462.     }
2463.     return (const char *) gl.lua_ver;
2464. }
2465. 
2466. RESTORE_WARNING_CONDEXPR_IS_CONSTANT
2467. 
2468. /***
2469.  *** SANDBOX / HARDENING CODE
2470.  ***/
2471. /*
2472.  * Tracing the sandbox:
2473.  * 1. Make sure CHRONICLE and LIVELOG are defined in config.h.
2474.  * 2. Rebuild the game.
2475.  * 3. Run the game and do whatever you want to check with lua.
2476.  * 4. Find the logged information in livelog.
2477.  *
2478.  * Logging format in livelog:
2479.  * <livelog leader>message=LUASTATS <TYPE> <SID>:<TAG> 
2480.  * where:
2481.  *  TYPE
2482.  *     DONE rough number of step taken during the life of the VM
2483.  *     DMEM memory in use at destruction of VM
2484.  *     PCAL rough number of steps during lua_pcall
2485.  *     PMEM memory in use after lua_pcall returns
2486.  *  SID     a small integer identifying the Lua VM instance
2487.  *  TAG     a string from the nhl_luapcall call
2488.  *  DATA    memory: rough number of bytes in use by the VM
2489.  *          steps: rough number of steps by the VM(see NHL_SB_STEPSIZE)
2490.  */
2491. #ifdef NHL_SANDBOX
2492. 
2493. enum ewhen {NEVER, IFFLAG, EOT};
2494. struct e {
2495.     enum ewhen when;
2496.     const char *fnname;
2497. };
2498. 
2499. /* NHL_BASE_BASE - safe things */
2500. static struct e ct_base_base[] = {
2501.     { IFFLAG, "ipairs" },
2502.     { IFFLAG, "next" },
2503.     { IFFLAG, "pairs" },
2504.     { IFFLAG, "pcall" },
2505.     { IFFLAG, "select" },
2506.     { IFFLAG, "tonumber" },
2507.     { IFFLAG, "tostring" },
2508.     { IFFLAG, "type" },
2509.     { IFFLAG, "xpcall" },
2510.     { EOT, NULL }
2511. };
2512. 
2513. /* NHL_BASE_ERROR - not really safe--might not want Lua to kill the process */
2514. static struct e ct_base_error[] = {
2515.     { IFFLAG, "assert" }, /* ok, calls error */
2516.     { IFFLAG, "error" },  /* ok, calls G->panic */
2517.     { NEVER, "print" },   /* not ok - calls lua_writestring/lua_writeline
2518.                            * which write to stdout */
2519.     { NEVER, "warn" },    /* not ok - calls lua_writestringerror which writes
2520.                            * to stderr */
2521.     { EOT, NULL }
2522. };
2523. 
2524. /* NHL_BASE_META - metatable access */
2525. static struct e ct_base_meta[] = {
2526.     { IFFLAG, "getmetatable" },
2527.     { IFFLAG, "rawequal" },
2528.     { IFFLAG, "rawget" },
2529.     { IFFLAG, "rawlen" },
2530.     { IFFLAG, "rawset" },
2531.     { IFFLAG, "setmetatable" },
2532.     { EOT, NULL }
2533. };
2534. 
2535. /* NHL_BASE_GC - questionable safety */
2536. static struct e ct_base_iffy[] = {
2537.     { IFFLAG, "collectgarbage" },
2538.     { EOT, NULL }
2539. };
2540. 
2541. /* NHL_BASE_UNSAFE - include only if required */
2542. /* TODO: if NHL_BASE_UNSAFE is ever used, we need to wrap lua_load with
2543.  * something to forbid mode=="b" */
2544. static struct e ct_base_unsafe[] = {
2545.     { IFFLAG, "dofile" },
2546.     { IFFLAG, "loadfile" },
2547.     { IFFLAG, "load" },
2548.     { EOT, NULL }
2549. };
2550. 
2551. /* no ct_co_ tables; all fns at same level of concern */
2552. /* no ct_string_ tables; all fns at same level of concern */
2553. /* no ct_table_ tables; all fns at same level of concern (but
2554.    sort can take a lot of time and can't be caught by the step limit */
2555. /* no ct_utf8_ tables; all fns at same level of concern */
2556. 
2557. 
2558. /* possible ct_debug tables - likely to need changes */
2559. static struct e ct_debug_debug[] = {
2560.     { NEVER,  "debug" },          /* uses normal I/O so needs re-write */
2561.     { IFFLAG, "getuservalue" },
2562.     { NEVER,  "gethook" },        /* see sethook */
2563.     { IFFLAG, "getinfo" },
2564.     { IFFLAG, "getlocal" },
2565.     { IFFLAG, "getregistry" },
2566.     { IFFLAG, "getmetatable" },
2567.     { IFFLAG, "getupvalue" },
2568.     { IFFLAG, "upvaluejoin" },
2569.     { IFFLAG, "upvalueid" },
2570.     { IFFLAG, "setuservalue" },
2571.     { NEVER,  "sethook" },        /* used for memory and step limits */
2572.     { IFFLAG, "setlocal" },
2573.     { IFFLAG, "setmetatable" },
2574.     { IFFLAG, "setupvalue" },
2575.     { IFFLAG, "setcstacklimit" },
2576.     { EOT, NULL }
2577. };
2578. static struct e ct_debug_safe[] = {
2579.     { IFFLAG, "traceback" },
2580.     { EOT, NULL }
2581. };
2582. 
2583. /* possible ct_os_ tables */
2584. static struct e ct_os_time[] = {
2585.     { IFFLAG, "clock" },          /* is this portable? XXX */
2586.     { IFFLAG, "date" },
2587.     { IFFLAG, "difftime" },
2588.     { IFFLAG, "time" },
2589.     { EOT, NULL }
2590. };
2591. 
2592. static struct e ct_os_files[] = {
2593.     { NEVER, "execute" },         /* not portable */
2594.     { NEVER, "exit" },
2595.     { NEVER, "getenv" },
2596.     { IFFLAG, "remove" },
2597.     { IFFLAG, "rename" },
2598.     { NEVER, "setlocale" },
2599.     { NEVER, "tmpname" },
2600.     { EOT, NULL }
2601. };
2602. 
2603. 
2604. #define DROPIF(flag, lib, ct) \
2605.     nhl_clearfromtable(L, !!(lflags & flag), lib, ct)
2606. 
2607. staticfn void
2608. nhl_clearfromtable(lua_State *L, int flag, int tndx, struct e *todo)
2609. {
2610.     while (todo->when != EOT) {
2611.         lua_pushnil(L);
2612.         /* if we load the library at all, NEVER items must be erased
2613.          * and IFFLAG items should be erased if !flag */
2614.         if (todo->when == NEVER || !flag) {
2615.             lua_setfield(L, tndx, todo->fnname);
2616.         }
2617.         todo++;
2618.     }
2619. }
2620. #endif
2621. 
2622. /*
2623. XXX
2624. registry["org.nethack.nethack.sb.fs"][N]=
2625.     CODEOBJECT
2626.     {
2627.         modepat: PATTERN,
2628.         filepat: PATTERN
2629.     }
2630. CODEOBJECT
2631.     if string then if pcall(string,mode, dir, file)
2632.     if table then if mode matches pattern and filepat ma....
2633. or do we use a real regex engine? (which we don't have and I just
2634.  argued against adding)
2635. 
2636. return values from "call it":
2637.     accept - file access granted
2638.     reject - file access denied
2639.     continue - try next element
2640.     fail - error.  deny and call impossible/panic
2641. */
2642. 
2643. /* stack indexes:
2644.  * -1       table to index with ename
2645.  * params   file
2646.  * params+1 [mode]
2647.  */
2648. /*
2649.  * Problem: NetHack doesn't have a regex engine and Lua doesn't give
2650.  *  C access to pattern matching.  There are 3 poor solutions:
2651.  * 1. Import ~5K lines of code in a dozen files from FreeBSD. (Upside - we
2652.  *    could use it in other places in NetHack.)
2653.  * 2. Hack up lstrlib.c to give C direct access to the pattern matching code.
2654.  * 3. Create a Lua state just to do pattern matching.
2655.  * We're going to do #3.
2656.  */
2657. #ifdef notyet
2658. staticfn boolean
2659. start_luapat(void)
2660. {
2661.     int rv;
2662.     /* XXX set memory and step limits */
2663.     nhl_sandbox_info sbi = { NHL_SB_STRING, 0, 0, 0 };
2664. 
2665.     if ((luapat = nhl_init(&sbi)) == NULL)
2666.         return FALSE;
2667. 
2668.     /* load a pattern matching function */
2669.     rv = luaL_loadstring(
2670.                          luapat,
2671.               "function matches(s,p) return not not stringm.match(s,p) end");
2672.     if (rv != LUA_OK) {
2673.         panic("start_luapat: %d", rv);
2674.     }
2675.     return TRUE;
2676. }
2677. #endif
2678. 
2679. staticfn void
2680. end_luapat(void)
2681. {
2682.     if (luapat) {
2683.         lua_close(luapat);
2684.         luapat = NULL;
2685.     }
2686. }
2687. 
2688. #ifdef notyet
2689. staticfn int
2690. opencheckpat(lua_State *L, const char *ename, int param)
2691. {
2692.     /* careful - we're using 2 different and unrelated Lua states */
2693.     const char *string;
2694.     int rv;
2695. 
2696.     lua_pushliteral(luapat, "matches");     /* function             -0,+1 */
2697. 
2698.     string = lua_tolstring(L, param, NULL); /* mode or filename     -0,+0 */
2699.     lua_pushstring(luapat, string);                              /* -0,+1 */
2700. 
2701. 
2702.     (void) lua_getfield(L, -1, ename);       /* pattern              -0,+1 */
2703.     lua_pop(L, 1);                                               /* -1,+0 */
2704.     string = lua_tolstring(L, -1, NULL);                         /* -0,+0 */
2705.     lua_pushstring(luapat, string);                              /* -0,+1 */
2706. 
2707.     if (nhl_pcall(luapat, 2, 1)) {                               /* -3,+1 */
2708.         /* impossible("access check internal error"); */
2709.         return NHL_SBRV_FAIL;
2710.     }
2711.     rv = lua_toboolean(luapat, -1);                              /* -0,+0 */
2712. #if 0
2713.     if (lua_resetthread(luapat) != LUA_OK)
2714.         return NHL_SBRV_FAIL;
2715. is pop sufficient? XXX or wrong - look at the balance
2716. #else
2717.     lua_pop(luapat, 1);                                          /* -1,+0 */
2718. #endif
2719.     return rv ? NHL_SBRV_ACCEPT : NHL_SBRV_DENY;
2720. }
2721. #endif
2722. 
2723. /* put the table open uses to check its arguments on the top of the stack,
2724.  * creating it if needed
2725.  */
2726. #define HOOKTBLNAME "org.nethack.nethack.sb.fs"
2727. #ifdef notyet
2728. static int (*io_open)(lua_State *) = NULL; /* XXX this may have to be in
2729.                                             * struct g (gi now) TBD */
2730. #endif
2731. 
2732. void
2733. nhl_pushhooked_open_table(lua_State *L)
2734. {
2735.     int hot = lua_getfield(L, LUA_REGISTRYINDEX, HOOKTBLNAME);
2736. 
2737.     if (hot == LUA_TNONE) {
2738.         lua_newtable(L);
2739.         lua_pushvalue(L, -1);
2740.         lua_setfield(L, LUA_REGISTRYINDEX, HOOKTBLNAME);
2741.     }
2742. }
2743. 
2744. #ifdef notyet
2745. staticfn int
2746. hooked_open(lua_State *L)
2747. {
2748.     const char *mode;
2749.     static boolean never = TRUE;
2750.     const char *filename;
2751.     int params;
2752.     int hot;
2753. 
2754.     if (never) {
2755.         if (!start_luapat())
2756.             return NHL_SBRV_FAIL;
2757.         never = FALSE;
2758.     }
2759.     filename = luaL_checkstring(L, 1);
2760. 
2761.     /* Unlike io.open, we want to treat mode as non-optional. */
2762.     if (lua_gettop(L) < 2) {
2763.         lua_pushstring(L, "r");
2764.     }
2765.     mode = luaL_optstring(L, 2, "r");
2766. 
2767.     /* sandbox checks */
2768.     /* Do we need some ud from the calling state to let this be different for
2769.        each call without redoing the HO table??  Maybe for version 2. XXX */
2770. 
2771.     params = lua_gettop(L)-1;  /* point at first param */
2772.     nhl_pushhooked_open_table(L);
2773.     hot = lua_gettop(L);
2774. 
2775.     if (lua_type(L, hot) == LUA_TTABLE) {
2776.         int idx;
2777.         for (idx = 1;
2778.              lua_pushinteger(L, idx),
2779.                  lua_geti(L, hot, idx),
2780.                  !lua_isnoneornil(L, -1);
2781.              ++idx) {
2782.             /* top of stack is our configtbl[idx] */
2783.             switch (lua_type(L, -1)) {
2784.                 /* lots of options to expand this with other types XXX */
2785.             case LUA_TTABLE: {
2786.                 int moderv, filerv;
2787.                 moderv = opencheckpat(L, "modepat", params+1);
2788.                 if (moderv == NHL_SBRV_FAIL)
2789.                     return moderv;
2790.                 filerv = opencheckpat(L, "filepat", params);
2791.                 if (filerv == NHL_SBRV_FAIL)
2792.                     return moderv;
2793.                 if (filerv == moderv) {
2794.                     if (filerv == NHL_SBRV_DENY)
2795.                         return NHL_SBRV_DENY;
2796.                     if (filerv == NHL_SBRV_ACCEPT)
2797.                         goto doopen;
2798.                 }
2799.                 break; /* try next entry */
2800.             }
2801.             default:
2802.                 return NHL_SBRV_FAIL;
2803.             }
2804.         }
2805.     } else
2806.         return NHL_SBRV_DENY; /* default to "no" */
2807. 
2808.  doopen:
2809.     lua_settop(L, params + 1);
2810.     return (*io_open)(L);
2811. }
2812. 
2813. staticfn boolean
2814. hook_open(lua_State *L)
2815. {
2816.     boolean rv = FALSE;
2817.     if (!io_open) {
2818.         int tos = lua_gettop(L);
2819.         lua_pushglobaltable(L);
2820.         if (lua_getfield(L, -1, "io") != LUA_TTABLE)
2821.             goto out;
2822.         lua_getfield(L, -1, "open");
2823.         /* The only way this can happen is if someone is messing with us,
2824.          * and I'm not sure even that is possible. */
2825.         if (!lua_iscfunction(L, -1))
2826.             goto out;
2827.         /* XXX This is fragile: C11 says casting func* to void*
2828.          * doesn't have to work, but POSIX says it does.  So it
2829.          * _should_ work everywhere but all we can do without messing
2830.          * around inside Lua is to try to keep the compiler quiet. */
2831.         io_open = (int (*)(lua_State *)) lua_topointer(L, -1);
2832.         lua_pushcfunction(L, hooked_open);
2833.         lua_setfield(L, -1, "open");
2834.         rv = TRUE;
2835.  out:
2836.         lua_settop(L, tos);
2837.     }
2838.     return rv;
2839. }
2840. #endif
2841. 
2842. DISABLE_WARNING_CONDEXPR_IS_CONSTANT
2843. 
2844. #ifdef NHL_SANDBOX
2845. staticfn void
2846. nhlL_openlibs(lua_State *L, uint32_t lflags)
2847. {
2848.     /* translate lflags from user-friendly to internal */
2849.     if (NHL_SB_DEBUGGING & lflags) {
2850.         lflags |= NHL_SB_DB_SAFE;
2851.     }
2852.     /* only for debugging the sandbox integration */
2853.     if (NHL_SB_ALL & lflags) {
2854.         lflags = -1;
2855.     } else if (NHL_SB_SAFE & lflags) {
2856.         lflags |= NHL_SB_BASE_BASE;
2857.         lflags |= NHL_SB_COROUTINE;
2858.         lflags |= NHL_SB_TABLE;
2859.         lflags |= NHL_SB_STRING;
2860.         lflags |= NHL_SB_MATH;
2861.         lflags |= NHL_SB_UTF8;
2862.     } else if (NHL_SB_VERSION) {
2863.         lflags |= NHL_SB_BASE_BASE;
2864.     }
2865. #ifdef notyet
2866. /*  Handling I/O is complex, so it's not available yet.  I'll
2867. finish it if and when we need it. (keni)
2868.     - hooked open; array of tuples of (r/w/rw/a/etc, directory pat, file pat)
2869. 
2870. {"close", io_close},    but with no args closes default output, so needs hook
2871. {"flush", io_flush},
2872. {"lines", io_lines},    hook due to filename
2873. {"open", io_open},  hooked version:
2874.     only safe if mode not present or == "r"
2875.         or WRITEIO
2876.     only safe if path has no slashes
2877.         XXX probably need to be: matches port-specific list of paths
2878.         WRITEIO needs a different list
2879.     dlb integration?
2880.     may need to #define l_getc (but that wouldn't hook core)
2881.         may need to #define fopen/fread/fwrite/feof/ftell (etc?)
2882.         ugh: lauxlib.c uses getc() below luaL_loadfilex
2883.             override in lua.h?
2884.         ugh: liolib.c uses getc() below g_read->test_eof
2885.             override in lua.h?
2886. {"read", io_read},
2887. {"type", io_type},
2888. {"input", io_input},    safe with a complex hook, but may be needed for read?
2889. WRITEIO:    needs changes to hooked open?
2890. {"output", io_output},  do we want to allow access to default output?
2891.   {"write", io_write},
2892. UNSAFEIO:
2893.   {"popen", io_popen},
2894.   {"tmpfile", io_tmpfile},
2895. */
2896. #endif
2897. 
2898.     if (lflags & NHL_SB_BASEMASK) {
2899.         int baselib;
2900.         /* load the entire library ... */
2901.         luaL_requiref(L, LUA_GNAME, luaopen_base, 1);
2902. 
2903.         baselib = lua_gettop(L);
2904. 
2905.         /* ... and remove anything unsupported or not requested */
2906.         DROPIF(NHL_SB_BASE_BASE, baselib, ct_base_base);
2907.         DROPIF(NHL_SB_BASE_ERROR, baselib, ct_base_error);
2908.         DROPIF(NHL_SB_BASE_META, baselib, ct_base_meta);
2909.         DROPIF(NHL_SB_BASE_GC, baselib, ct_base_iffy);
2910.         DROPIF(NHL_SB_BASE_UNSAFE, baselib, ct_base_unsafe);
2911. 
2912.         lua_pop(L, 1);
2913.     }
2914. 
2915.     if (lflags & NHL_SB_COROUTINE) {
2916.         luaL_requiref(L, LUA_COLIBNAME, luaopen_coroutine, 1);
2917.         lua_pop(L, 1);
2918.     }
2919.     if (lflags & NHL_SB_TABLE) {
2920.         luaL_requiref(L, LUA_TABLIBNAME, luaopen_table, 1);
2921.         lua_pop(L, 1);
2922.     }
2923. #ifdef notyet
2924.     if (lflags & NHL_SB_IO) {
2925.         luaL_requiref(L, LUA_IOLIBNAME, luaopen_io, 1);
2926.         lua_pop(L, 1);
2927.         if (!hook_open(L))
2928.             panic("can't hook io.open");
2929.     }
2930. #endif
2931.     if (lflags & NHL_SB_OSMASK) {
2932.         int oslib;
2933.         luaL_requiref(L, LUA_OSLIBNAME, luaopen_os, 1);
2934.         oslib = lua_gettop(L);
2935.         DROPIF(NHL_SB_OS_TIME, oslib, ct_os_time);
2936.         DROPIF(NHL_SB_OS_FILES, oslib, ct_os_files);
2937.         lua_pop(L, 1);
2938.     }
2939. 
2940.     if (lflags & NHL_SB_STRING) {
2941.         luaL_requiref(L, LUA_STRLIBNAME, luaopen_string, 1);
2942.         lua_pop(L, 1);
2943.     }
2944.     if (lflags & NHL_SB_MATH) {
2945.         luaL_requiref(L, LUA_MATHLIBNAME, luaopen_math, 1);
2946.         /* XXX Note that math.random uses Lua's built-in xoshiro256**
2947.          * algorithm regardless of what the rest of the game uses.
2948.          * Fixing this would require changing lmathlib.c. */
2949.         lua_pop(L, 1);
2950.     }
2951.     if (lflags & NHL_SB_UTF8) {
2952.         luaL_requiref(L, LUA_UTF8LIBNAME, luaopen_utf8, 1);
2953.         lua_pop(L, 1);
2954.     }
2955.     if (lflags & NHL_SB_DBMASK) {
2956.         int dblib;
2957.         luaL_requiref(L, LUA_DBLIBNAME, luaopen_debug, 1);
2958.         dblib = lua_gettop(L);
2959.         DROPIF(NHL_SB_DB_DB, dblib, ct_debug_debug);
2960.         DROPIF(NHL_SB_DB_SAFE, dblib, ct_debug_safe);
2961.         lua_pop(L, 1);
2962.     }
2963. }
2964. #endif
2965. 
2966. RESTORE_WARNING_CONDEXPR_IS_CONSTANT
2967. 
2968. staticfn void *
2969. nhl_alloc(void *ud, void *ptr, size_t osize UNUSED, size_t nsize)
2970. {
2971.     nhl_user_data *nud = ud;
2972. 
2973.     if (nsize == 0) {
2974.         if (ptr != NULL) {
2975.             free(ptr);
2976.         }
2977.         return NULL;
2978.     }
2979. 
2980.     /* Check nud->L because it will be NULL during state init. */
2981.     if (nud && nud->L && nud->memlimit) { /* this state is size limited */
2982.         if (nhl_getmeminuse(nud->L) > nud->memlimit)
2983.             return NULL;
2984.     }
2985. 
2986.     return re_alloc(ptr, (unsigned) nsize);
2987. }
2988. 
2989. DISABLE_WARNING_UNREACHABLE_CODE
2990. 
2991. staticfn int
2992. nhl_panic(lua_State *L)
2993. {
2994.     const char *msg = lua_tostring(L, -1);
2995. 
2996.     if (msg == NULL)
2997.         msg = "error object is not a string";
2998.     panic("unprotected error in call to Lua API (%s)\n", msg);
2999.     /*NOTREACHED*/
3000.     return 0; /* return to Lua to abort */
3001. }
3002. 
3003. RESTORE_WARNING_UNREACHABLE_CODE
3004. 
3005. /* called when lua issues a warning message; the text of the message
3006.    is passed to us in pieces across multiple function calls */
3007. staticfn void
3008. nhl_warn(
3009.     void *userdata UNUSED,
3010.     const char *msg_fragment,
3011.     int to_be_continued) /* 0: last fragment; 1: more to come */
3012. {
3013.     size_t fraglen, buflen = strlen(gl.lua_warnbuf);
3014. 
3015.     if (msg_fragment && buflen < sizeof gl.lua_warnbuf - 1) {
3016.         fraglen = strlen(msg_fragment);
3017.         if (buflen + fraglen > sizeof gl.lua_warnbuf - 1)
3018.             fraglen = sizeof gl.lua_warnbuf - 1 - buflen;
3019.         (void) strncat(gl.lua_warnbuf, msg_fragment, fraglen);
3020.     }
3021.     if (!to_be_continued) {
3022.         paniclog("[lua]", gl.lua_warnbuf);
3023.         gl.lua_warnbuf[0] = '\0';
3024.     }
3025. }
3026. 
3027. #ifdef NHL_SANDBOX
3028. staticfn void
3029. nhl_hookfn(lua_State *L, lua_Debug *ar UNUSED)
3030. {
3031.     nhl_user_data *nud;
3032. 
3033.     (void) lua_getallocf(L, (void **) &nud);
3034. 
3035.     if (nud->steps <= NHL_SB_STEPSIZE)
3036.         longjmp(nud->jb, 1);
3037. 
3038.     nud->steps -= NHL_SB_STEPSIZE;
3039.     nud->statctr++;
3040. }
3041. #endif
3042. 
3043. staticfn lua_State *
3044. nhlL_newstate(nhl_sandbox_info *sbi, const char *name)
3045. {
3046.     nhl_user_data *nud = 0;
3047. 
3048.     if (sbi->memlimit || sbi->steps || sbi->perpcall) {
3049.         nud = nhl_alloc(NULL, NULL, 0, sizeof (struct nhl_user_data));
3050.         if (!nud)
3051.             return 0;
3052.         nud->L = NULL;
3053.         nud->memlimit = sbi->memlimit;
3054.         nud->perpcall = 0; /* set up below, if needed */
3055.         nud->steps = 0;
3056.         nud->osteps = 0;
3057.         nud->flags = sbi->flags; /* save reporting flags */
3058.         nud->statctr = 0;
3059. 
3060.         if (name) {
3061.             nud->name = name;
3062.         }
3063.         nud->sid = ++gl.lua_sid;
3064.     }
3065. 
3066.     lua_State *L = lua_newstate(nhl_alloc, nud
3067. #if LUA_VERSION_NUM >= 505
3068.                                , 0
3069. #endif
3070.                                );
3071.     if (!L)
3072.         panic("NULL lua_newstate");
3073. 
3074.     if(nud) nud->L = L;
3075.     lua_atpanic(L, nhl_panic);
3076. #if LUA_VERSION_NUM == 504
3077.     lua_setwarnf(L, nhl_warn, L);
3078. #endif
3079. 
3080. #ifdef NHL_SANDBOX
3081.     if (nud && (sbi->steps || sbi->perpcall)) {
3082.         if (sbi->steps && sbi->perpcall)
3083.             impossible("steps and perpcall both non-zero");
3084.         if (sbi->perpcall) {
3085.             nud->perpcall = sbi->perpcall;
3086.         } else {
3087.             nud->steps = sbi->steps;
3088.             nud->osteps = sbi->steps;
3089.         }
3090.         lua_sethook(L, nhl_hookfn, LUA_MASKCOUNT, NHL_SB_STEPSIZE);
3091.     }
3092. #endif
3093. 
3094.     return L;
3095. }
3096. 
3097. #endif /* !SFCTOOL */
3098. 
3099. /*
3100. (See end of comment for conclusion.)
3101. to make packages safe, we need something like:
3102.     if setuid/setgid (but does NH drop privs before we can check? TBD)
3103.         unsetenv LUA_CPATH, LUA_CPATH_5_4 (and this needs to change with
3104.           version) maybe more
3105.     luaopen_package calls getenv
3106.         unsetenv(LUA_PATH_VAR)
3107.         unsetenv(LUA_CPATH_VAR)
3108.         unsetenv(LUA_PATH_VAR LUA_VERSUFFIX)
3109.         unsetenv(LUA_CPATH_VAR LUA_VERSUFFIX)
3110.                     package.config
3111.                     oackage[fieldname] = path
3112.             NB: LUA_PATH_DEFAULT and LUA_CPATH_DEFAULT must be safe
3113.                 or we must setenv LUA_PATH_VAR and LUA_CPATH_VAR to something
3114.                 safe
3115.             or we could just clean out the searchers table?
3116.                 package.searchers[preload,Lua,C,Croot]
3117. also, can setting package.path to something odd get Lua to load files
3118.  it shouldn't? (see docs package.searchers)
3119. set (and disallow changing) package.cpath (etc?)
3120. loadlib.c:
3121.     lsys_load -> dlopen     Kill with undef LUA_USE_DLOPEN LUA_DL_DLL
3122.     searchpath -> readable -> fopen
3123.         <- ll_searchpath
3124.         <- findfile <- {searchers C, Croot, Lua}
3125. Probably the best thing to do is replace G.require with our own function
3126. that does whatever it is we need and completely ignore the package library.
3127. */
3128. /*
3129. TODO:
3130. docs
3131. unfinished functionality & design
3132. commit, cleanup, commit with SHA1 of full code version
3133. BUT how do we compact the current history?
3134.     new branch, then compress there
3135. XXX
3136. */
3137. 
3138. /*nhlua.c*/