接收者参数与冒号
Coddy 面向 C 开发者的 Lua 课程的第 34 课,共 48 课。
在 C 中,修改记录的函数通常会接收指向该记录的指针。调用者会显式传入它的地址,被调用者则使用指针访问各个字段。Lua 方法也采用类似的接收者约定,但表引用本身已经标识了对象。使用冒号定义函数时,会自动提供一个名为 self 的第一个参数。使用冒号调用时,会自动提供接收者参数。也可以使用点调用,只要你自行传入接收者,就像第二次调用所展示的那样。
C
#include <stdio.h>
struct Counter { int n; };
static void counter_add(struct Counter *self, int amount)
{
self->n += amount;
}
int main(void)
{
struct Counter counter = {2};
counter_add(&counter, 3);
counter_add(&counter, 4);
printf("%d\n", counter.n);
return 0;
}Lua
local counter = {n = 2}
function counter:add(amount)
self.n = self.n + amount
end
counter:add(3)
counter.add(counter, 4)
print(counter.n)移植时的陷阱
Lua 不会仅仅因为你从表中获取了一个函数,就自动绑定接收者。调用 counter.add(3) 时,数字会作为 self 传入。请使用 counter:add(3) 或 counter.add(counter, 3)。
挑战
简单Model.new(n) 会存储 n。实现 Model:add(delta),更新 n 并返回它。输入包含初始 n,后面跟着一个增量。应用会调用冒号方法并返回其结果。
编辑 app.lua、model.lua。可见的锁定文件 main.lua 会将标准输入读入一个行序列,调用 app.run(lines),并用一个末尾换行符打印其返回值。不要打印诊断信息,也不要更改模块名称。空输入会得到一个空序列。所有数字输入都足够小,不会溢出。
公共 API 检查:Model.new(n) 会存储独立的 n 状态。add(delta) 会返回并存储更新后的 n,包括负增量和零增量。锁定的驱动程序会在调用 app.run 前检查此行为。检查成功时不会打印任何内容。
亲手试试
-- 公共 API 检查
do
local Model=require("model")
local a,b=Model.new(2),Model.new(10)
assert(a:add(3)==5 and a.n==5,"add must return and store the updated n")
assert(a:add(-7)==-2 and a:add(0)==-2,"add must support negative and zero deltas")
assert(b.n==10,"add must not mutate another instance")
end
local app = require("app")
local lines = {}
for line in io.lines() do lines[#lines + 1] = line end
print(app.run(lines))
这节课包含一个小测验。开始学习即可作答,并记录你的进度。
面向 C 开发者的 Lua中的所有课
自己练习: Lua 在线编译器