Discussion:
Override a local function/variable from another function
Elijah Frederickson
2013-10-16 23:41:00 UTC
Permalink
How can I override a local function/variable that's in a different
function/environment?

e.g. (yes, its Lua 5.1):

function override(orig, replacement)
local x = getfenv(2)
for k, v in pairs(x) do
if v==origthen x[k] = replacement end
end
end

local function a() print"a" end
local old_a = a
override(a, function() print"overridden"; old_a() end)
local x = 1
override(x, 2)
print(x) -- should print 2 now


That code works if function 'a' is not local, but is global. I know that
local variables are directly mapped to registers, so I don't even know if
it's possible. Any suggestions, for 5.1 or 5.2?



Thanks,
Elijah Frederickson
--
~ mlnlover11 ~
https://github.com/mlnlover11
Dirk Laurie
2013-10-17 04:48:40 UTC
Permalink
debug.getinfo, debug.setlocal, debug.setupvalue add up to a lot of power.
Maybe enough to do what you want.
Post by Elijah Frederickson
How can I override a local function/variable that's in a different
function/environment?
function override(orig, replacement)
local x = getfenv(2)
for k, v in pairs(x) do
if v==origthen x[k] = replacement end
end
end
local function a() print"a" end
local old_a = a
override(a, function() print"overridden"; old_a() end)
local x = 1
override(x, 2)
print(x) -- should print 2 now
That code works if function 'a' is not local, but is global. I know that
local variables are directly mapped to registers, so I don't even know if
it's possible. Any suggestions, for 5.1 or 5.2?
Thanks,
Elijah Frederickson
--
~ mlnlover11 ~
https://github.com/mlnlover11
Rob Kendrick
2013-10-17 08:34:37 UTC
Permalink
Post by Dirk Laurie
debug.getinfo, debug.setlocal, debug.setupvalue add up to a lot of power.
Maybe enough to do what you want.
I'm more interested in why somebody would want this :)

B.
Elijah Frederickson
2013-10-17 17:17:49 UTC
Permalink
Thanks Dirk! I was able to get it working with this.

@Rob: Have you ever heard of mobile substrate/cydia substrate? It lets you
override C/ObjC functions dynamically. I was trying to bring something like
that to Lua, purely for educational purposes of course. For example, it
could be used to debug calls to something like table.insert.
Post by Rob Kendrick
Post by Dirk Laurie
debug.getinfo, debug.setlocal, debug.setupvalue add up to a lot of power.
Maybe enough to do what you want.
I'm more interested in why somebody would want this :)
B.
--
~ mlnlover11 ~
https://github.com/mlnlover11
Loading...