From 7c4365458097600cd8220b39a56f98fabaaf347e Mon Sep 17 00:00:00 2001 From: Pasi Kallinen Date: Sun, 16 Mar 2025 20:29:24 +0200 Subject: [PATCH] Lua: allow functions for some optional strings Those places that use get_table_str_opt() to get an optional string value can instead use a function that returns a string. This can be used for example in quest data lua table, or some table fields in the lua api bindings, or the dungeon definition. For example, in quest.lua text = "You again sense %l pleading for help.", could be replaced with text = function() return "You again sense %l pleading for help."; end, which of course allows using lua to build the string. --- src/nhlua.c | 11 ++++++++++- 1 file changed, 10 insertions(+), 1 deletion(-) diff --git a/src/nhlua.c b/src/nhlua.c index dc2c64911..6342f949c 100644 --- a/src/nhlua.c +++ b/src/nhlua.c @@ -1021,9 +1021,18 @@ char * get_table_str_opt(lua_State *L, const char *name, char *defval) { const char *ret; + int ltyp; lua_getfield(L, -1, name); - ret = luaL_optstring(L, -1, defval); + ltyp = lua_type(L, -1); + if (ltyp == LUA_TSTRING || ltyp == LUA_TNIL) { + ret = luaL_optstring(L, -1, defval); + } else if (ltyp == LUA_TFUNCTION) { + nhl_pcall_handle(L, 0, 1, "get_table_str_opt", NHLpa_panic); + ret = luaL_optstring(L, -1, defval); + } else { + nhl_error(L, "get_table_str_opt: no string"); + } if (ret) { lua_pop(L, 1); return dupstr(ret);