How do compilers of dynamically typed languages handle changes in non-local variables?

Viewed 95

Take the following Lua code (which I use because Lua is compiled to bytecode before being interpreted):

local myVar = "h";

local function printer()
    print(myVar)
end;

printer();

myVar = 7;

printer();

The output to this is h, then, on a new line, 7.

Due to the dynamic typing of the language, I imagine the variable must be re-allocated in memory due to the change in data type. Proceeding with this assumption, myVar must refer to different places at different parts of the script. If that is the case, it makes sense to me that there must be two versions of printer compiled: one pre-change, and one post-change.

I also considered that each variable may have some memory location allocated to it, and that the given memory location can be checked to find the currently allocated location for the variable's value. If this is the case, I suppose reference types like tables have a reference stored to at the referred-to location (a double-reference)?

So, is a function compiled for each different version of it that might run? Are variable location changes tracked with a pointer? Or is some other process going on here?

1 Answers

Due to the dynamic typing of the language, I imagine the variable must be re-allocated in memory due to the change in data type.

Objects take up memory; variables are merely holders for objects. A variable can hold any object; when you invoke myvar (wherever this may be), it goes to the location where myvar holds its object and retrieves it. When you do myvar = <something>, it goes to the location where myvar holds its object and switches the held object to be <something>.

Any memory beyond what is needed to hold an object is part of the object, not of the variable.

In particular for Lua, a local variable like myvar is a specific location on a particular Lua stack. An object can be stored into that location, and the object can be retrieved from it. The location is the same regardless of where you read the data from, assuming you are in the same instance of the Lua code that created the local variable.

Related