最近有很多同学问lua中 类型的 引用和拷贝的问题
我打算记录一下
Lua中基本类型分别为:nil、boolean、lightuserdata 、number、string、userdata、function、thread 、table;
从lua.h中可以看出
#define LUA_TNIL 0
#define LUA_TBOOLEAN 1
#define LUA_TLIGHTUSERDATA 2
#define LUA_TNUMBER 3
#define LUA_TSTRING 4
#define LUA_TTABLE 5
#define LUA_TFUNCTION 6
#define LUA_TUSERDATA 7
#define LUA_TTHREAD 8
```
(其中 number 在lua中叫实数,lua中没有整数, number其实是c/c++一个 double的类型。)
lua 中 table (和经过语法糖包装的table形式变量) 用 = 进行变量 赋值 都将会是引用,
其他都是拷贝(number, function等)。(若有错误,欢迎各位拍砖)
但是table有个例外
local t1 = {"table"}
local t2 = t1
t2 = nil
这里不会影响t1.
```
部分测试代码 和结果:
local src = {"aa", "bb", "cc"}
local des = src
print("1 src :", table.concat(src, ", "))
print("1 des :", table.concat(des, ", "))
src = "dd"
print("2 src :", table.concat(src, ", "))
print("2 des :", table.concat(des, ", "))
des = "ee"
print("3 src :", table.concat(src, ", "))
print("3 des :", table.concat(des, ", "))
des = nil
print("4 src :", table.concat(src or {"empty"}, ", "))
print("4 des :", table.concat(des or {"empty"}, ", "))
local fun1 = function(...)
print("fun1", ...)
end
local fun2 = fun1
fun1("fun1")
fun2("fun2")
fun2 = function(...)
print("fun2", ...)
end
fun1("fun1")
fun2("fun2")
```
luajit执行结果
1 src : aa, bb, cc
1 des : aa, bb, cc
2 src : dd, bb, cc
2 des : dd, bb, cc
3 src : ee, bb, cc
3 des : ee, bb, cc
4 src : ee, bb, cc
4 des : empty
fun1 fun1
fun1 fun2
fun1 fun1
fun2 fun2
lua VM对string 的管理机制为: string 永远只保留一份唯一 的copy。
所以 string使用 = 赋值操作,应该是 引用。
如果想copy table,
quick在functions.lua 提供了 clone()函数。
