diff --git a/moon/init.lua b/moon/init.lua index 4e0d68f..b6178db 100644 --- a/moon/init.lua +++ b/moon/init.lua @@ -2,7 +2,33 @@ if not moon or not moon.inject then module("moon", package.seeall) end local util = require("moonscript.util") +local lua = { + debug = debug +} dump = util.dump +debug = { + upvalue = function(fn, k, v) + local upvalues = { } + local i = 1 + while true do + local name = lua.debug.getupvalue(fn, i) + if name == nil 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]) + return value + else + return lua.debug.setupvalue(fn, upvalues[k], v) + end + end +} run_with_scope = function(fn, scope, ...) local old_env = getfenv(fn) local env = setmetatable({ }, { diff --git a/moon/init.moon b/moon/init.moon index adf0eed..84f496b 100644 --- a/moon/init.moon +++ b/moon/init.moon @@ -4,10 +4,33 @@ if not moon or not moon.inject util = require "moonscript.util" +lua = { :debug } + export * dump = util.dump +debug = { + upvalue: (fn, k, v) -> + upvalues = {} + i = 1 + while true + name = lua.debug.getupvalue(fn, i) + break if name == nil + upvalues[name] = i + i += 1 + + if not upvalues[k] + error "Failed to find upvalue: " .. tostring k + + if not v + _, value = lua.debug.getupvalue fn, upvalues[k] + value + else + lua.debug.setupvalue fn, upvalues[k], v +} + + -- run a function with scope injected before its function environment run_with_scope = (fn, scope, ...) -> old_env = getfenv fn