String Interpolation for Lua (Mudlet)

OwynOwyn USMember Posts: 31 ✭✭
Ok, so this is super handy. It works like python's print(f"{a} {b}"), but it isn't python. I didn't write a majority of this. Most of it was found on a site you can reach by googling lua string interpolation, but it was written for Lua 5.2, not 5.1 so this is my fix -- tested and working well:
</code><code><span>--EXAMPLE USE NOTE:</span>
--Make an alias and do something like:
--local a = 150
--print(f"I want to punch {target} in the face {a} times.")

--Or: local t = { str = "I want to punch {target} in the face {a} times." }
--print(f(t.str))

<span>function f(str)</span>
	local load = load
	if _VERSION == "Lua 5.1" then
		load = <span>function(code, name, _, env)</span>
		local fn, err = loadstring(code, name)
		if fn then
			return fn
		else
			return nil, err
		end
	end
end
	local outer_env = _ENV
	return (str:gsub("%b{}", <span>function(block)</span>
		local code = block:match("{(.*)}")
		local exp_env = {}
		setmetatable(exp_env, { __index = <span>function(_, k)</span>
			local stack_level = 5
			while debug.getinfo(stack_level, "") ~= nil do
				local i = 1
				repeat
					local name, value = debug.getlocal(stack_level, i)
					if name == k then
						return value
					end
					i = i + 1
				until name == nil
				stack_level = stack_level + 1
			end
			return rawget(outer_env, k)
		end })
		local fn, err = load("return "..code, "expression `"..code.."`", "t", exp_env)
		if fn then
			return tostring(fn())
		else
			error(err, 0)
		end
	end))
<span>end</span>


TheophilusAodan
Sign In or Register to comment.