Skip to content

Instantly share code, notes, and snippets.

@Deco
Created January 24, 2012 20:43
Show Gist options
  • Select an option

  • Save Deco/1672452 to your computer and use it in GitHub Desktop.

Select an option

Save Deco/1672452 to your computer and use it in GitHub Desktop.
Extensions to the default Lua functions for flexibility through metamethods
do -- base function reimplementations
do _G.rawtype = _G.rawtype or _G.type
local meta, override
function _G.type(v)
local vtype = rawtype(v)
if vtype ~= "table" and vtype ~= "userdata" then return vtype end
meta = debug.getmetatable(v)
if meta then
override = rawget(meta, "__type")
if override then
if rawtype(override) == "function" then
return override(v) or rawtype(v)
else
return override
end
end
end
return rawtype(v)
end
end
do _G.rawtostring = _G.rawtostring or _G.tostring
-- the default already checks __tostring!
end
do _G.rawtonumber = _G.rawtonumber or _G.tonumber
local meta, override
function _G.tonumber(v)
local n = rawtonumber(v)
if n then return n end -- this optimisation makes it nearly as fast as
-- the original for numbers and strings
meta = debug.getmetatable(v)
if meta then
override = rawget(meta, "__tonumber")
if override then
if rawtype(override) == "function" then
return override(v)
else
return override
end
end
end
return rawtonumber(v)
end
end
do _G.rawtobool = _G.rawtobool or _G.tobool or function(v) return v and true or false end
local meta, override
function _G.tobool(v)
if rawtype(v) == "boolean" then return v end
meta = debug.getmetatable(v)
if meta then
override = rawget(meta, "__tobool")
if override then
if rawtype(override) == "function" then
return override(v)
else
return override
end
end
end
return v and true or false--rawtobool(v)
end
end
do _G.rawnext = _G.rawnext or _G.next
local meta, override
function _G.next(v, k)
meta = debug.getmetatable(v)
if meta then
override = rawget(meta, "__next")
if override then
if rawtype(override) == "function" then
return override(v, k)
else
return override
end
end
end
return rawnext(v, k)
end
end
do _G.rawunpack = _G.rawunpack or _G.unpack
local meta, override
function _G.unpack(v)
meta = debug.getmetatable(v)
if meta then
override = rawget(meta, "__unpack")
if override then
if rawtype(override) == "function" then
return override(v)
else
return override
end
end
end
return rawunpack(v)
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment