2

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?

6
  • What do you mean by a "memory address"? A C function? Commented Oct 15, 2014 at 1:22
  • What are you trying to achieve? Commented Oct 15, 2014 at 1:41
  • @ColonelThirtyTwo the memory address of a Lua function Commented Oct 15, 2014 at 1:45
  • @lhf I'm saving the state of my program and when I try to load that state back, the only variable that is not changing back properly is a variable that holds a function, so clearly programState[frame].myDynamicFuncVar = myDynamicFuncVar is not working properly when I attempt to load myDynamicFuncVar = programState[frame].myDynamicFuncVar taking a look at these states after a load shows that this function is returning a different memory address than it was on the save. Basically I need a proper save procedure for this variable. Commented Oct 15, 2014 at 1:51
  • 5
    Since functions are dynamically allocated, saving their memory address is pointless, as it will almost definitely change from one run to another. You can serialize functions with string.dump then load it back with loadstring or load, but that gets rid of your upvalues. Commented Oct 15, 2014 at 1:53

1 Answer 1

4

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.