当前位置: 首页 > ds >正文

lua中 list.last = last 和list[last]=value区别

在 Lua 中,list.last = last 和 list[last] = value是两种完全不同的操作,核心区别在于它们操作的是表(table)的不同元素类型:

1. list.last = last这是给表 list 添加 / 修改一个名为 last 的键值对(字段),其中 last 是字符串类型的键。

相当于 list["last"] = lastLua 中 . 语法是 [""] 语法的简写,键名会被当作字符串)。

无论 last 变量的值是什么(数字、字符串等),这里的键始终是字符串 "last"

示例:

local list = {}
local last = 100list.last = last  -- 等价于 list["last"] = 100
print(list.last)  -- 输出 100
print(list["last"])  -- 输出 100(与上一行等价)
print(list[last])  -- 输出 nil(因为键是字符串"last",不是数字100)

2. list[last] = value这是给表 list 添加 / 修改一个以 last 变量的值为键的键值对,键的类型由 last 变量的值决定(可以是数字、字符串、表等)

• 若 last 是数字,就是操作表的数组部分(类似数组的索引)。

• 若 last 是字符串,就是操作表的字段(等价于 list.last = value 当且仅当 last 是字符串 "last" 时)。

示例:

local list = {}
local last = 3  -- last是数字3
local value = "hello"list[last] = value  -- 等价于 list[3] = "hello"
print(list[3])  -- 输出 "hello"
print(list.last)  -- 输出 nil(因为没有键"last")

另一个例子(last 是字符串):

local list = {}
local last = "last"  -- last是字符串"last"
local value = 200list[last] = value  -- 等价于 list["last"] = 200,也等价于 list.last = 200
print(list.last)  -- 输出 200(此时与list[last]效果一致)

总结

表达式含义键的类型典型用途
list.last = last给表添加键为 "last" 的字段固定为字符串给表添加描述性属性(如元信息)
list[last] = value给表添加键为 last 变量值的字段由 last 决定动态操作表元素(如数组索引)

简单说:list.last 是固定操作名为 "last" 的字段,而 list[last] 是操作以 last 变量值为键的字,后者更灵活,可动态指定键。

http://www.xdnf.cn/news/17087.html

相关文章:

  • 悬挂的绳子,它的函数方程是什么样子的?
  • HiveMQ 2024.9 设计与开发文档
  • Android 之 MVVM架构
  • 大语言模型的解码策略:贪婪解码与波束搜索
  • [硬件电路-133]:模拟电路 - 信号处理电路 - 电荷放大器概述、工作原理、常见芯片、管脚定义
  • 使用ASIWebPageRequest库编写Objective-C下载器程序
  • 动感按钮:如何打造交互感十足的点击动画效果
  • Python-初学openCV——图像预处理(五)
  • GitHub 趋势日报 (2025年08月02日)
  • 机器学习第四课之决策树
  • C++-二叉树OJ题
  • 分布式文件系统05-生产级中间件的Java网络通信技术深度优化
  • ubuntu24.04安装selenium、edge、msedgedriver
  • Leetcode 12 java
  • 2.0 vue工程项目的创建
  • C++:STL中的栈和队列的适配器deque
  • 8.1.3 TiDB集群方案雨Replication原理
  • Python批处理深度解析:构建高效大规模数据处理系统
  • Docker--解决x509: certificate signed by unknown authority
  • 创建型设计模式:对象诞生的艺术与智慧
  • Java小红书源码1:1还原uniapp_仿小红书源码
  • 01.MySQL 安装
  • HTTPS的概念和工作过程
  • git配置公钥/密钥
  • MySQL梳理三:查询与优化
  • ThinkPHP 与 Vue.js 结合的全栈开发模式
  • Flink程序关键一步:触发环境执行
  • ubuntu syslog中appindicator报错解决
  • ABP VNext + CloudEvents:事件驱动微服务互操作性
  • 系统学习算法:专题十六 字符串