lua-users home
lua-l archive

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]


On Sep 22, 2013, at 2:51 AM, Tim Hill <drtimhill@gmail.com> wrote:

> So let's put aside upvalues for a moment. In Lua there are broadly two types of values, "value" types and "reference" types (this is conceptually similar to Java and many other languages). Value types are things like number and booleans, while reference types are tables, coroutines, userdata (strings are special, skip those for now).
> 
> Consider a simple assignment of two variables: "x = y". If y contains a value type, then x will get a *copy* of the value in y. This is kind of common sense, if y contains 10, then after the assignment x will contain 10. Changing the value of y later will not alter the value of x. But if y contains a reference type value (such as table), then "x = y" will make x reference the *same* value. In this case, changes made to the table via y will *also* appear in x, and vice-versa.
> 
> So, for values the semantics are copy, but for reference types the semantics are reference. This applies to assignment, argument passing, and return values.

You are correctly describing the implementation of Lua values, perhaps not the simplest semantics for some people. There is an equivalent way to look at this: the semantics for all values is by reference; some values are mutable (tables, userdata), most values are not mutable (numbers, strings, booleans). Rephrasing your second paragraph above,

Consider a simple assignment of two variables: "x = y". If y refers to a value, then x will get the same reference. Changing the value of y later (changing what y refers to) will not alter the value of x (what x refers to). But if y contains a reference to a mutable value (such as table), changes made to the value (table) via y will *also* appear in the value (table) x refers to, and vice-versa. Of course, non-mutable values such as numbers or strings cannot be changed like this.

e