0

每个对象都有一个可以关联变量的引用,对吗?

这些参考资料是什么样的?这是你做 print(table1) 时得到的吗?

0x100108fb0 例如?

如果是这样,是否有一个函数可以显示字符串和数字等更原始类型的引用?

4

2 回答 2

4

不要混淆对象、引用和变量。

引用Lua 5.2 参考手册

表、函数、线程​​和(完整的)用户数据值都是对象:变量实际上并不包含这些值,只是对它们的引用。

因此,如果变量的值是类型nil或数字,则该变量实际上包含它,而不是仅引用它。此类型不涉及参考。我不知道为什么参考手册的上述引用中省略了字符串;也许是因为字符串是不可变的,对于 Lua 程序员来说,变量是否包含字符串引用或值都没有区别。但是,从技术上讲——从 C 的角度来看——字符串是从变量引用的,而不是包含的。

引用只是一个指针,即被引用对象在内存中的地址。当打印为十六进制数字时,它真的“看起来”像0x100108fb0.

如果是这样,是否有一个函数可以显示字符串和数字等更原始类型的引用?

正如我所写,对于后者,根本没有任何参考资料。对于字符串,无法在普通 Lua 中打印地址,但无论如何您都不需要知道它。

您可能还想阅读《Lua参考手册中的编程》的相应部分。

于 2013-03-03T11:59:30.283 回答
1

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.

于 2013-03-04T05:40:34.123 回答