LUA表与函数的深入理解

local heroInfo = {}

--直接打印 table的名字,就会输出该table的内存地址
print("表地址---------------",heroInfo)


--注意区别PrintInfo,PrintInfo2与TestSelf两个函数中self的不同
--有什么不?

heroInfo.PrintInfo = function(self, x)--这里的self仅是我们定义的普通参数,可以写成任何样子
    print("PrintInfo-------------x=", x)

    self.gender = "men"
    print("gender=", heroInfo.gender) --输出 gender=men,为什么?
end

--定义函数时使用点号,self并不存在
heroInfo.PrintInfo2 = function(x)
    print("PrintInfo2-------------self=", self, ",x=", x)
end

--定义函数时使用冒号,系统自动把表地址赋值给了self
function heroInfo:TestSelf(x)--注意,参数并没有写self
    print("TestSelf--------------self=", self, ",x=", x)
    self.name = "jim"
    print("heroInfo.name=",heroInfo.name)
    heroInfo.name = "none"
    print("self.name=", self.name)
end

--函数调用
--使用冒号调用时,系统会自动把表地址传给函数的第一个参数,使用点号则不会
--这个参数可以写成self,也可以写成其它任何样子
--这类似于C++中的this指针
heroInfo:PrintInfo("hello")--改成点号调用测试下
heroInfo:PrintInfo2("hello", "world")--改成点号调用测试下
heroInfo:TestSelf(10)--改成点号调用测试下

--lua中table是一个引用型变量,就像C#中的数组,类对象
local self = heroInfo --从此以后ref与heroInfo就指向同一个表了

print("self.name=",self.name, "self.gender=",self.gender)
self.name = "monster"
self.gender = "unknown"
print("heroInfo.name=", heroInfo.name, "heroInfo.gender=", heroInfo.gender)
原文地址:https://www.cnblogs.com/timeObjserver/p/6437491.html