Is there a name for expressions that return what they are, instead of a reference?

StackOverflow https://stackoverflow.com/questions/14831760

  •  09-03-2022
  •  | 
  •  

I've noticed that strings, numbers, bool and nil data seem to be straight forward to work with. But when it comes to functions, tables, etc. you get a reference instead of the actual object.

Is there a name for this phenomenon? Is there terminology that describes the distinction between the way these 2 sets of types are handled?

a = "hi"    
b = 1
c = true
d = nil
e = {"joe", "mike"}
f = function () end
g = coroutine.create(function () print("hi") end)

print(a) --> hi
print(b) --> 1
print(c) --> true
print(d) --> nil
print(e) --> table: 0x103350
print(f) --> function: 0x1035a0
print(g) --> thread: 0x103d30
有帮助吗?

解决方案 2

.Net (Microsoft Visual Basic, Visual C++ and C#) would describe them as value types and reference types, where reference types refer to a value by reference and value types hold the actual values.

I don't think lua puts too much thought into it given that it's supposed to be a simpler interpreted language and ultimately it doesn't matter as much because lua is a fairly weakly typed language (ie it doesn't enforce type safety beyond throwing an error when you try to use operations on types they can't be used on).

Either way, most programmers in my experience understand them as 'value types' and 'reference types', so I'd say they're the two terms it's best to stick with.

其他提示

What you're seeing here is an attempt by the compiler to return a string representation of the object. For simple object types the __tostring implementation is provided already, but for other more complex types there is no intuitive way of returning a string representation.

See Lua: give custom userdata a tostring method for more information which might help!

In Lua, numbers are values, everything else is accessible by reference only. But the different behavior on print is just because there's no way to actually print functions (and while tables could have a default behavior for print, they don't - possibly because they're allowed to have cyclic references).

What you are seeing is the behavior of the print function. It will its arguments by using tostring on them. print could be implemented by using io.write like this (simplified a bit):

function print(...)
    local args = {n = select('#',...), ...}
    for i=1,args.n do
        io.write(tostring(args[i]), '\t')
    end
    io.write('\n')
end

You should notice the call to tostring. By default it returns the representation of numbers, booleans and strings. Since there is no sane default way to convert other types to a string, it only displays the type and a useless internal pointer to the object (so that you can differentiate instances). You can view the source here.

You will be surprised, but there is no value/reference distinction in Lua. :-)
Please read here and here.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top