当前位置:网站首页>lua-table引用传递和值传递
lua-table引用传递和值传递
2022-08-11 05:31:00 【星际行走】
function test1(tt)
tt = {1, 3, 5}
end
function test2(tt)
tt[1] = 2
tt["a"] = "hello"
end
t = {4, 5, 6}
test1(t)
for k,v in pairs(t) do
print(v)
end
print("------")
t = {4, 5, 6}
test2(t)
for k,v in pairs(t) do
print(v)
endtest1改不了外部的tt的值,
test2能改变外部tt的值,但是前提是传入的外部tt不能为nil。如果tt为nil,在函数内再分配空间、赋值,外部的tt还是为nil。可以先在外部给tt分配内存 tt = {},然后再作为参数传递给test2,此时在test2里面修改tt的值,外部tt也会改变。
lua中table的引用传递只能是修改该table对象的内部元素,对table对象的复制操作,无法做到引用传递的效果。
所谓值传递,其实是一种拷贝传递,函数调用时,在函数栈中, 拷贝实参的值到形参,所以,对形参的修改当然不会影响实参。
要做到函数内部修改,在外部可见,一种方式是传递地址,如这里的table的内部元素,另一种是传递引用,引用传递需要语言级别的支持,如c的&引用传递符号,表示该变量不是拷贝传递,形参是实参的别名。(其实底层的实现用的是指针)
边栏推荐
- jdbc接口文档参考,jdbc接口方法逻辑探究
- Manufacturer Push Platform-Huawei Access
- Asis2016 books null off by one
- Day 73
- 第一章 Verilog语言和Vivado初步使用
- The role of the port
- 本地服务配置内网穿透实现微信公众号整合
- Lua 快速入门(五)——协程(thread)
- IndexError: index 9 is out of bounds for axis 0 with size 9;数组下标溢出问题
- 连接数据库时出现WARN: Establishing SSL connection without server‘s identity verification is not recommended.
猜你喜欢

【LeetCode-389】找不同

Node stepping on the pit 80 port is occupied

Tinker's self-introduction

C-8月1日-递归与动态内存管理

Jetpack use exception problem collection

ARM assembly instruction ADR and LDR

js learning advanced (event senior pink teacher teaching notes)

Content Size Fitter的使用

The whole process of Tinker access --- configuration

Day 75
随机推荐
Lua 快速入门(三)——表(Table)
Manufacturer Push Platform-Huawei Access
USB in NRZI to encode the data
【无标题】
Day 79
Jetpack use exception problem collection
Open Source Machine Learning Database OpenMLDB Contributor Program Fully Launched
The role of the port
【LeetCode-162】寻找峰值
函数使用记录
C-动态内存管理
父子节点数据格式不一致的树状列表实现
heap2 (tcache attack,house of orange)
自己动手写RISC-V的C编译器-02语法描述方法和递归下降解析
品优购项目实战笔记
【LeetCode-56】合并区间
C语言-6月8日-给定一个字符数组‘i am a student’ 统计字符a的个数并进行输出
PyQt5中调用.ui转换的.py文件代码解释
OpenGL WSAD按键操作和鼠标移动操控摄像机Camera类
Real-time Feature Computing Platform Architecture Methodology and Practice Based on OpenMLDB