在 Lua 中需要 help/Clarification

Need help/Clarification in Lua

昨天看到Lua在“爱情框架”下使用oop方法编写的代码,所以我尝试通过更改一些变量来编写相同的代码以更好地理解它。

Class = require 'lib/class'-- I'm using Class library https://github.com/vrld/hump/blob/master/class.lua

Bala = Class{__includes = Shubham}

-- here I'm Calling Bala Class

chawal = Bala {
           market = "A-Market",
           Rashan = "poha"
        }

-- Here I've initialized Bala Class using 'init' to pass a argument inside it.

function Bala:init(def)
   Shubham.init(self, def)
end

-- Here I've created Shubham class and pass the same argument.
Shubham = Class{}

function Shubham:init(def)
  self.market = def.market
  self.Rashan = def.Rashan
end

print(chawal.market)
The output is table: 00800320

所以我的问题是如何通过 print() 调用来自 Shubham Class 的参数并仅使用终端 我的第二个问题是为什么我们在 Shubham.init(self, def) 中使用 'self' 这一行的实际含义是什么。

您刚才输入的代码顺序不正确。

当执行一个 lua 文件时,你将从上到下处理它,所以如果你从文件的较低部分引用一些东西,它还不会 exist/have 被加载.

第一个例子在这里:

chawal = Bala {
           market = "A-Market",
           Rashan = "poha"
        }

-- Here I've initialized Bala Class using 'init' to pass a argument inside it.

function Bala:init(def)
   Shubham.init(self, def)
end

您正在执行的操作会在定义 Bala:init 之前调用 Bala:init,class 库会“挽救”您的错误,但这只会让您认为代码“有效”

这应该是各部分的正确顺序:

Class = require 'lib/class'

Shubham = Class{}

function Shubham:init(def)
  self.market = def.market
  self.Rashan = def.Rashan
end

Bala = Class{__includes = Shubham}

function Bala:init(def)
   Shubham.init(self, def)
end

chawal = Bala {
           market = "A-Market",
           Rashan = "poha"
        }

print(chawal.market)

输出:

A-Market