Skip to content

Instantly share code, notes, and snippets.

@LPGhatguy
Created October 17, 2015 09:08
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 LPGhatguy/c8d24b3a95a203e8522d to your computer and use it in GitHub Desktop.
Save LPGhatguy/c8d24b3a95a203e8522d to your computer and use it in GitHub Desktop.
Converts snake_case libraries (like excessive moe's) to camelCase.
local function breakSnake(id)
if (type(id) ~= "string") then
return id
end
return (id:gsub("(%w)_(%a)", function(a, b)
return a .. b:upper()
end))
end
local function makeSnake(id)
if (type(id) ~= "string") then
return id
end
return (id:gsub("(%w)(%u)", function(a, b)
return a .. "_" .. b:lower()
end))
end
local function aliasStatic(object)
local keys = {}
for key in pairs(object) do
table.insert(keys, key)
end
for i, key in ipairs(keys) do
object[breakSnake(key)] = object[key]
end
end
local function alias(object)
local meta = getmetatable(object)
local index = meta and meta.__index
local newindex = meta and meta.__newindex
local getter, setter
if (index) then
getter = function(this, key)
return index(this, makeSnake(key))
end
else
getter = function(this, key)
return rawget(this, makeSnake(key))
end
end
if (newindex) then
setter = function(this, key, value)
return newindex(this, makeSnake(key), value)
end
else
setter = function(this, key, value)
return rawset(this, makeSnake(key), value)
end
end
if (meta) then
meta.__index = getter
meta.__newindex = setter
else
setmetatable(object, {
__index = getter,
__newindex = setter
})
end
end
return {
alias = alias,
aliasStatic = aliasStatic,
breakSnake = breakSnake,
makeSnake = makeSnake
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment