Lua初学习 9-13_05 Lua中table 模仿 C#类模版 (Lua方法调用方式)

1-1: 函数调用

a = {}

function a.fun01(n) print(n) end

调用:

   a.fun01(1)  -----> 1              ===》这种方式 调方法,第一个参数 n 就是传入进去的参数 1 ,参数列表(1)

   a:fun01(2)  -----> table: 0012c9e3(内存地址)    ===》第一个参数 n 是table a,  :调 传入的参数列表为(a , 2)

1-2:函数声明

a = {}

声明方式 01: . 点  声明

function a.fun02(n) print(self,n) end 

我们下面用两种方式调:

a.fun02(1)  -----> nil   1  (.声明方法,没有传入self table)

a:fun02(1)  -----> nil    table内存地址 (.声明方法只接受一个参数(n),:调用方法传入的是(table,1) 1被舍弃)

声明方式 02:: 冒号 声明

function a:fun02(n) print(self,n) end

下面用两种方式调:

a.fun02(1) -----> 1   nil (函数接受参数(self,n)   传入的参数(1) -- self = 1,n没有值=nil)

a:fun03(1) -----> table内存地址 1  (函数接受的参数(self,n)  传入的参数(table,1) -- self = table,n = 1)

 

 

2:类 new 对象  (模拟)

human = {age=0,add = function (this,num) this.age=this.age+num end}

 ====>human table 看作为C#里面的一个类

student = human =====>这种方式像是new了一个C#类;这个时候可以访问 student age字段 add方法

 

这个时候student调方法:

student.add(student,1)  ------>age+1

student:add(1)              ------>age+1  如1所说,冒号:调用方法,传入的参数会自动带一个table,参数列表(table,1)

 

3:类的继承 (模拟)

              如之前:

              a = {}  b = {}

  我们让a作为b的父类

  setmetatable(b,{__index = a})

 

4:多重继承

cat= { miao = "miao"}
dog = {wang= "wang"}
cow = {mei = "mei"}


human = { age = 0}
function human:__index(k)
return cat[k] or dog[k] or cow[k]
end

student = {}
setmetatable(student,human)

print(student.wang)

====>student的元表为human, human里面的元方法重写, 模拟多继承

 

5:类的构造函数

human = { age=0, id = 0, name ="human"}
function human.new(t)
  local proxy = {}
  proxy.age = t[1]
  proxy.id = t[2]
  proxy.name = t[3]
  setmetatable(proxy,human)
  human.__index = human
  return proxy
end
function human.Say()
  print("human say")
end



coco = human.new({23,10001,"cocotang"})
print(coco.id)      ----->10001
print(coco.name) ---->cocotang


pika = human.new({30,10002,"pika"})

print(coco.id)    ----->10001
print(coco.name) ----->cocotang
pika.name = "new pika"

print(pika.id)   ------>10002
print(pika.name)  ----->new pika 

 

 

 

原文地址:https://www.cnblogs.com/cocotang/p/5869269.html