theman
theman

Reputation: 345

load Lua function variable via memory address?

Is it possible to load in a function variable via the memory address of the requested function?

aFunctionVar = loadFunc(memAddress)
if type(aFunctionVar) == 'function' then "this var is a function!" end

is something like loadFunc() possible in Lua?

Upvotes: 2

Views: 1595

Answers (1)

Colonel Thirty Two
Colonel Thirty Two

Reputation: 26549

Lua functions (as with functions in most scripting languages) don't have fixed internal addresses [1]. Every time Lua executes a function expression, it allocates a new closure for it at some arbitrary address. The address of a function closure from some previous run is completely useless; it's virtually impossible that there is a function at that address during the current run.

Even if you do have the memory address from a function in the same process, vanilla Lua doesn't provide any way of 'loading' it, neither from inside the script nor from the C API.

If you need to serialize functions, you can use string.dump, which will return a string of the bytecode of the passed function, which can be loaded using loadstring or load depending on the Lua version. Note that this bytecode is independent of the source function's code; the function will do whatever it did whenever it was dumped, regardless of your changes to the source code. Also, string.dump cannot serialize the function's upvalues.


[1] Heck, even C functions might not have fixed addresses from run to run; functions in shared libraries need to be able to be placed anywhere in memory to avoid conflicts.

Upvotes: 4

Related Questions