Lua中为何函数修改变量会改变其父表变量值?——表引用赋值导致属性同步变更的疑问
: Syntax in Lua Let's cut straight to the answer: The variable v and Assertion point to the exact same table object—they aren't separate copies. When you modify the key property via v, you're actually changing the property of that shared table, which is why Assertion reflects the change too. Let's break down how this works in Lua step by step:
1. Lua Tables Are Reference Types
In Lua, tables are reference types. That means when you write v = Assertion, you aren't duplicating the contents of the Assertion table. Instead, you're giving v a reference (think of it like a pointer) to the exact same table that Assertion points to. It's like making a copy of a house key—both keys open the same house, so any changes you make inside the house are visible with either key.
2. What the : Syntax Actually Does
Your function function Assertion:brl(ky) is Lua syntactic sugar. It's exactly equivalent to writing:
function Assertion.brl(self, ky) self.key = ky end
Similarly, calling v:brl(5) is shorthand for:
v.brl(v, 5)
Since v and Assertion refer to the same table, the self parameter in the function is that shared table. When you set self.key = ky, you're directly modifying the key property of that single table object.
3. Line-by-Line Walkthrough of Your Code
Let's trace exactly what happens as your code runs:
Assertion = { key }: Here,keyis an undefined variable, so it defaults tonil. TheAssertiontable'skeyproperty isnil, hence the firstprint(Assertion.key)outputsnil.v = Assertion:vnow references the same table asAssertion.v:brl(5): This passesv(the shared table) as theselfparameter tobrl, setting the table'skeyproperty to5.- The final two
printstatements: Whether you accesskeyviaAssertionorv, you're looking at the same table's property—so both output5.
4. How to Create Independent Tables (If Needed)
If you want v to be a separate table that doesn't affect Assertion, you need to manually copy the original table's contents. For example:
function copyTable(t) local newTable = {} for k, val in pairs(t) do newTable[k] = val end return newTable end Assertion = { key } v = copyTable(Assertion) v:brl(5) print(Assertion.key) -- Outputs nil print(v.key) -- Outputs 5
Now v is a distinct table, so modifying its properties won't touch the original Assertion table.
内容的提问来源于stack exchange,提问作者Anon

