You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Lua中为何函数修改变量会改变其父表变量值?——表引用赋值导致属性同步变更的疑问

Understanding Table References and the : 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, key is an undefined variable, so it defaults to nil. The Assertion table's key property is nil, hence the first print(Assertion.key) outputs nil.
  • v = Assertion: v now references the same table as Assertion.
  • v:brl(5): This passes v (the shared table) as the self parameter to brl, setting the table's key property to 5.
  • The final two print statements: Whether you access key via Assertion or v, you're looking at the same table's property—so both output 5.

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.29 09:27:32