Skip to content

Instantly share code, notes, and snippets.

@daurnimator
Last active August 29, 2015 14:23
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save daurnimator/dedd793e6f9b1f8d6b0c to your computer and use it in GitHub Desktop.
Save daurnimator/dedd793e6f9b1f8d6b0c to your computer and use it in GitHub Desktop.
lexically scoped string methods
--[[
11:22:54 daurnimator I've always thought local string metatables etc would be cool
11:23:02 daurnimator I'd want them lexically scoped
11:24:54 daurnimator you could make it so that string's __index used debug.getlocal to find the _ENV
11:25:22 daurnimator that way mystring.foo would always be equal to _ENV.string.foo
]]
string = {
sub = function()
return "something else"
end;
}
print("PRE", ("foo"):sub(2))
local string_mt = debug.getmetatable("")
local strsub = string_mt.__index.sub
function string_mt:__index(k)
local func = debug.getinfo(2, "f").func
local name, env = debug.getupvalue(func, 1)
if name == "_ENV" or (name ~= nil and strsub(name, 1, 1) == "(") then
local env_string = env.string
if env_string ~= nil then
return env_string[k]
end
end
end
print("POST", ("foo"):sub(2))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment