From 3864dc58333d3ada27f9227d07b55d2ee375b3d2 Mon Sep 17 00:00:00 2001 From: Indev Date: Sat, 27 Jul 2024 03:26:37 +0300 Subject: [PATCH] Lets not compile lua code multiple time each frame x) --- src/k_kart.c | 14 ++++++------ src/lua_script.c | 55 ++++++++++++++++++++++++++++++++++++++++-------- src/lua_script.h | 1 + 3 files changed, 54 insertions(+), 16 deletions(-) diff --git a/src/k_kart.c b/src/k_kart.c index 972336447..d820c8366 100644 --- a/src/k_kart.c +++ b/src/k_kart.c @@ -3497,7 +3497,7 @@ void K_DriftDustHandling(mobj_t *spawner) fixed_t spawny = P_RandomRange(-spawnrange, spawnrange)< watertrail_maxstate && watertrailunderlay_minstate > watertrailunderlay_maxstate)) // Check if some of these were freeslot'd in wrong order diff --git a/src/lua_script.c b/src/lua_script.c index 4d43a38de..6db95a08b 100644 --- a/src/lua_script.c +++ b/src/lua_script.c @@ -364,6 +364,17 @@ void LUA_DumpFile(const char *filename) } #endif +static void createMathLibState(void) +{ + mL = lua_newstate(LUA_Alloc, NULL); + lua_atpanic(mL, LUA_Panic); + + // open only enum lib + lua_pushcfunction(mL, LUA_EnumLib); + lua_pushboolean(mL, true); + lua_call(mL, 1, 0); +} + fixed_t LUA_EvalMathEx(const char *word, const char **error) { char buf[1024], *b; @@ -373,15 +384,7 @@ fixed_t LUA_EvalMathEx(const char *word, const char **error) // make a new state so SOC can't interefere with scripts // allocate state if (mL == NULL) - { - mL = lua_newstate(LUA_Alloc, NULL); - lua_atpanic(mL, LUA_Panic); - - // open only enum lib - lua_pushcfunction(mL, LUA_EnumLib); - lua_pushboolean(mL, true); - lua_call(mL, 1, 0); - } + createMathLibState(); // change ^ into ^^ for Lua. strcpy(buf, "return "); @@ -420,6 +423,40 @@ fixed_t LUA_EvalMath(const char *word) return res; } +// A hack to prevent lua from crashing game if constant doesn't exist +static int lua_get_constant(lua_State *L) +{ + lua_pushvalue(mL, LUA_GLOBALSINDEX); + lua_pushvalue(L, 1); + lua_gettable(L, -2); + + return 1; +} + +fixed_t LUA_GetConstant(const char *word) +{ + if (mL == NULL) + createMathLibState(); + + fixed_t res = 0; + + lua_pushcfunction(mL, lua_get_constant); + lua_pushstring(mL, word); + + if (lua_pcall(mL, 1, 1, 0) == 0) + { + if (lua_isnumber(mL, -1)) + res = lua_tointeger(mL, -1); + } + else + { + // Pop error message + lua_pop(mL, 1); + } + + return res; +} + void LUA_InvalidateMathlibCache(const char *name) { // No state => no cache => nothing to invalidate :3 diff --git a/src/lua_script.h b/src/lua_script.h index 9513f0b11..e16911d9c 100644 --- a/src/lua_script.h +++ b/src/lua_script.h @@ -46,6 +46,7 @@ void LUA_DumpFile(const char *filename); #endif fixed_t LUA_EvalMathEx(const char *word, const char **error); fixed_t LUA_EvalMath(const char *word); +fixed_t LUA_GetConstant(const char *word); // Need better name for this ;-; void LUA_InvalidateMathlibCache(const char *name);