Igorio
Igorio

Reputation: 948

What do 'references' to objects in Lua look like?

Each object has a reference with which a variable can be associated with, correct?

What do these references look like? Is it what you get when you do print(table1) ?

0x100108fb0 for example?

If so, is there a function that can show the reference of the more primitive types like string and number?

Upvotes: 0

Views: 1374

Answers (2)

Igorio
Igorio

Reputation: 948

Each object has a reference with which a variable can be associated with, correct?

No. Lua represents values as tagged unions (type, value). For variables representing number, bool or nil, the value is stored directly in the union. For string, table, function, userdata and thread, the value is a pointer (reference), or set of pointers that correlates to the memory location of the object's header.

What do these references look like?

As Oberon said, the reference points to a spot in memory, when represented in hex looks like 0x0..

If so, is there a function that can show the reference of the more primitive types like string and number?

number, bool or nil, don't have any reference. For strings, there is no standard way to print their addresses in Lua. For table, function and thread you can use print(). Not sure about userdata, this you may need to define yourself.

Many of the implementation details of these types are covered in plain language in this article.

Upvotes: 2

Oberon
Oberon

Reputation: 3249

Don't confuse objects, references and variables.

Quoting from the Lua 5.2 Reference Manual:

Tables, functions, threads, and (full) userdata values are objects: variables do not actually contain these values, only references to them.

So if the value of a variable is of type nil or number, the variable actually contains it, instead of only referencing it. There is no reference involved with this types. I don't know why strings are left out in the above quote from the reference manual; maybe because strings are immutable, it makes no difference for the Lua-programmer whether variables contain string-references or -values. However, technically -- from a C point of view -- strings are referenced from variables, not contained.

A reference is just a pointer, the address of the referenced object in memory. When printed as a hexadecimal number, it really "looks" like 0x100108fb0.

If so, is there a function that can show the reference of the more primitive types like string and number?

To the latter, as I wrote, there are no references at all. For strings, there is no way to print there addresses in plain Lua, but you won't need to know it anyway.

You might also want to read the appropriate section of the Programming in Lua Reference Manual.

Upvotes: 4

Related Questions