Coding With Fun
Home Docker Django Node.js Articles Python pip guide FAQ Policy

Understand points, colons, and self in the Lua language


May 12, 2021 Lua



In lua programming, you often encounter definitions and calls to functions, sometimes with dots, sometimes with colons, and here's a simple explanation of the principle. Such as:

Dot call:

-- 点号定义和点号调用:
girl = {money = 200}

function girl.goToMarket(girl ,someMoney)
    girl.money = girl.money - someMoney
end

girl.goToMarket(girl ,100)
print(girl.money)

Reference parameter self:

-- 参数self指向调用者自身(类似于c++里的this 指向当前类)
girl = {money = 200}

function girl.goToMarket(self ,someMoney)
    self.money = self.money - someMoney
end

girl.goToMarket(girl, 100)
print(girl.money)

Colon call:

-- 冒号定义和冒号调用:
girl = {money = 200}

function girl:goToMarket(someMoney)
    self.money = self.money - someMoney
end

girl:goToMarket(100)
print(girl.money)

The colon definition and colon call are actually the same effect as above, omitting the first hidden argument, which self points to the caller itself.

Summary: The colon simply omits the first argument, self, which points to the caller itself, and there is nothing special about it.

Quote blog post: http://www.xuebuyuan.com/1613223.html