( sf: LuaStackFrame, template: string, envAugmentation?: LuaTable, )
| 54 | * @returns The interpolated string. |
| 55 | */ |
| 56 | export async function interpolateLuaString( |
| 57 | sf: LuaStackFrame, |
| 58 | template: string, |
| 59 | envAugmentation?: LuaTable, |
| 60 | ): Promise<string> { |
| 61 | let result = ""; |
| 62 | let currentIndex = 0; |
| 63 | |
| 64 | while (true) { |
| 65 | const startIndex = template.indexOf("${", currentIndex); |
| 66 | if (startIndex === -1) { |
| 67 | result += template.slice(currentIndex); |
| 68 | break; |
| 69 | } |
| 70 | |
| 71 | result += template.slice(currentIndex, startIndex); |
| 72 | |
| 73 | // Find matching closing brace by counting nesting |
| 74 | let nestLevel = 1; |
| 75 | let endIndex = startIndex + 2; |
| 76 | while (nestLevel > 0 && endIndex < template.length) { |
| 77 | if (template[endIndex] === "{") { |
| 78 | nestLevel++; |
| 79 | } else if (template[endIndex] === "}") { |
| 80 | nestLevel--; |
| 81 | } |
| 82 | if (nestLevel > 0) { |
| 83 | endIndex++; |
| 84 | } |
| 85 | } |
| 86 | |
| 87 | if (nestLevel > 0) { |
| 88 | throw new LuaRuntimeError("Unclosed interpolation expression", sf); |
| 89 | } |
| 90 | |
| 91 | const expr = template.slice(startIndex + 2, endIndex); |
| 92 | try { |
| 93 | const parsedExpr = parseExpressionString(expr); |
| 94 | const env = createAugmentedEnv(sf, envAugmentation); |
| 95 | // Do `luaToString` before `luaValueToJS` to preserve tagged float |
| 96 | // formatting. |
| 97 | const luaResult = singleResult(await evalExpression(parsedExpr, env, sf)); |
| 98 | result += await luaToString(luaResult); |
| 99 | } catch (e: any) { |
| 100 | throw new LuaRuntimeError(`Error evaluating "${expr}": ${e.message}`, sf); |
| 101 | } |
| 102 | |
| 103 | currentIndex = endIndex + 1; |
| 104 | } |
| 105 | |
| 106 | return result; |
| 107 | } |
| 108 | |
| 109 | /** |
| 110 | * Converts an optional Lua options table into a `PrintOptions` object, |
no test coverage detected