From a1cebd8d0d36e8221c861364b98476d6a06df6ca Mon Sep 17 00:00:00 2001 From: Bruce Hill Date: Mon, 5 Feb 2018 17:33:26 -0800 Subject: [PATCH] Fix for debug.upvalue(). This should make it faster (stop scanning when it hits the desired upvalue) and more correct (allow setting an upvalue to a falsey or nil value: debug.upvalue(fn, 'foo', nil), which is different from debug.upvalue(fn, 'foo')). --- moon/init.lua | 19 +++++++++---------- moon/init.moon | 19 ++++++++----------- 2 files changed, 17 insertions(+), 21 deletions(-) diff --git a/moon/init.lua b/moon/init.lua index d4c2490..b828a02 100644 --- a/moon/init.lua +++ b/moon/init.lua @@ -25,25 +25,24 @@ type = function(value) return base_type end debug = setmetatable({ - upvalue = function(fn, k, v) - local upvalues = { } + upvalue = function(fn, k, ...) + local value = nil local i = 1 while true do - local name = lua.debug.getupvalue(fn, i) + local name + name, value = lua.debug.getupvalue(fn, i) if name == nil then + error("Failed to find upvalue: " .. tostring(k)) + end + if name == k then break end - upvalues[name] = i i = i + 1 end - if not upvalues[k] then - error("Failed to find upvalue: " .. tostring(k)) - end - if not v then - local _, value = lua.debug.getupvalue(fn, upvalues[k]) + if select("#", ...) == 0 then return value else - return lua.debug.setupvalue(fn, upvalues[k], v) + return lua.debug.setupvalue(fn, i, ...) end end }, { diff --git a/moon/init.moon b/moon/init.moon index 658d886..46d5ff1 100644 --- a/moon/init.moon +++ b/moon/init.moon @@ -18,23 +18,20 @@ type = (value) -> -- class aware type base_type debug = setmetatable { - upvalue: (fn, k, v) -> - upvalues = {} + upvalue: (fn, k, ...) -> + value = nil i = 1 while true - name = lua.debug.getupvalue(fn, i) - break if name == nil - upvalues[name] = i + name, value = lua.debug.getupvalue(fn, i) + if name == nil + error "Failed to find upvalue: " .. tostring k + break if name == k i += 1 - if not upvalues[k] - error "Failed to find upvalue: " .. tostring k - - if not v - _, value = lua.debug.getupvalue fn, upvalues[k] + if select("#", ...) == 0 value else - lua.debug.setupvalue fn, upvalues[k], v + lua.debug.setupvalue fn, i, ... }, __index: lua.debug -- run a function with scope injected before its function environment