Last active
August 29, 2015 14:23
-
-
Save daurnimator/dedd793e6f9b1f8d6b0c to your computer and use it in GitHub Desktop.
lexically scoped string methods
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
--[[ | |
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