Skip to content

Instantly share code, notes, and snippets.

@weswigham
Created November 5, 2013 04:33
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save weswigham/7313933 to your computer and use it in GitHub Desktop.
Save weswigham/7313933 to your computer and use it in GitHub Desktop.
You've always wanted method_missing in lua, right? This is a pretty close approximation.
--[[
Method missing should be an optional definition on any object.
If a method cannot be found, method_missing is called if available
]]
local field = '__method__missing'
function method_missing(selfs, func)
local meta = getmetatable(selfs)
local f
if meta then
f = meta.__index
else
meta = {}
f = rawget
end
meta.__index = function(self, name)
local v = f(self, name)
if v then
return v
end
rawget(self, name)[field] = function(...)
return func(self, name, ...)
end
end
setmetatable(selfs, meta)
end
debug.setmetatable(nil, { __call = function(self, ...)
if self[field] then
return self[field](...)
end
return nil
end, __index = function(self, name)
if name~=field then error("attempt to index a nil value") end
return getmetatable(self)[field]
end, __newindex = function(self, name, value)
if name~=field then error("attempt to index a nil value") end
getmetatable(self)[field] = value
end} )
return method_missing
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment