self와 콜론 호출
Coddy의 C# 개발자를 위한 Lua 코스 레슨. 48개 중 34번째.
C# 인스턴스 호출은 수신자를 암묵적으로 전달하고, 메서드 그룹 대리자는 해당 수신자를 유지합니다. Lua의 콜론 구문은 객체를 첫 번째 self 인수로 명시적으로 전달하며, 일반적인 점 호출은 그렇게 하지 않습니다. 특히 나중에 실행할 메서드를 저장할 때는 정의와 호출 규칙을 일치시키세요. Lua는 분리된 함수를 이전 테이블에 자동으로 바인딩하지 않습니다.
C#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
var counter=new Counter(); Action<int> add=counter.Add; add(3); Console.WriteLine(counter.N);
class Counter {public int N=2; public void Add(int n){N+=n;}}
Lua 5.1
local c={n=2}
function c:add(x) self.n=self.n+x end
c:add(3)
print(c.n)포팅 규칙
self 매개변수를 전달하려면 object:method(x) 또는 object.method(object,x)를 사용하세요.
챌린지
쉬움Model.new(n)은 n을 저장합니다. n을 업데이트하고 반환하는 Model:add(delta)를 구현하세요. 입력에는 초기 n과 그 뒤에 하나의 delta가 있습니다. 앱은 콜론 메서드를 호출하고 그 결과를 반환합니다.
app.lua, model.lua를 수정하세요. 잠금 상태로 표시된 main.lua는 stdin에서 줄의 연속을 읽고, app.run(lines)을 호출한 다음, 반환된 값을 마지막에 줄바꿈 하나와 함께 출력합니다. 진단 메시지를 출력하거나 모듈 이름을 변경하지 마세요. 입력이 비어 있으면 빈 연속이 됩니다. 모든 숫자 입력은 오버플로가 발생하지 않을 만큼 작습니다.
공개 API 확인: Model.new(n)은 서로 독립적인 n 상태를 저장합니다. add(delta)는 음수와 0인 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 컴파일러