Skip to content

Instantly share code, notes, and snippets.

@DarkWiiPlayer
Last active October 1, 2021 21:30
Show Gist options
  • Save DarkWiiPlayer/9cb8634aafe95885779282800088b526 to your computer and use it in GitHub Desktop.
Save DarkWiiPlayer/9cb8634aafe95885779282800088b526 to your computer and use it in GitHub Desktop.
local function locals(n)
n = n + 1
local result = {}
for i=1,math.huge do
name, value = debug.getlocal(n, i)
if not name then break end
result[name] = {value}
end
return result
end
local function quote(str)
return "'"..str:gsub("\\", "\\\\"):gsub("'", "\\'").."'"
end
local function I(str)
local locals = locals(2)
local env = setmetatable({}, {__index = function(self, idx)
if locals[idx] then
return locals[idx][1]
else
return _ENV[idx]
end
end})
-- For simplicity, only finds a single interpolation for now
local buffer = {}
local start = 1
while true do
local a = str:find('#{', start)
local b = str:find('}', a)
if not a or not b then
table.insert(buffer, quote(str:sub(start, -1)))
break
end
table.insert(buffer, quote(str:sub(start, a-1)))
table.insert(buffer, "tostring("..str:sub(a+2, b-1)..")")
start = b+1
end
return load("return "..table.concat(buffer, ".."), "interp", "bt", env)()
end
local x = 100
print(I"Hello world #{x} :)")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment