self와 콜론 호출
Coddy의 Java 개발자를 위한 Lua 코스 레슨. 48개 중 34번째.
Java 인스턴스 메서드는 암묵적으로 this를 전달받으며, 바인딩된 메서드 참조는 해당 리시버를 유지합니다. Lua의 콜론 구문은 첫 번째 self 인자로 객체를 명시적으로 전달하지만, 점 호출은 그렇지 않습니다. 정의와 호출 규칙을 일치시키고, 콜백이 테이블을 유지해야 하는 경우 분리된 메서드를 래핑하세요.
Java
import java.util.*;
import java.util.function.*;
import java.util.regex.*;
public class Main {
static class Counter {int n=2; void add(int x){n+=x;}}
public static void main(String[] args) throws Exception {
Counter counter=new Counter(); IntConsumer add=counter::add; add.accept(3); System.out.println(counter.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은 콜론 메서드를 호출하고 그 결과를 반환합니다.
app.lua, model.lua를 편집하세요. 표시된 잠긴 main.lua는 stdin을 읽어 줄의 연속으로 만들고, app.run(lines)를 호출하며, 반환된 값을 마지막 줄바꿈 하나와 함께 출력합니다. 진단 메시지를 출력하거나 모듈 이름을 변경하지 마세요. 빈 입력은 빈 연속을 반환합니다. 모든 숫자 입력은 오버플로가 발생하지 않을 정도로 충분히 작습니다.
공개 API 검사: Model.new(n)은 독립적인 n 상태를 저장합니다. add(delta)는 음수 및 0 delta를 포함하여 업데이트된 n을 반환하고 저장합니다. 잠겨 있는 드라이버는 app.run을 호출하기 전에 이 동작을 검사합니다. 이 검사는 성공 시 아무것도 출력하지 않습니다.
직접 해보기
-- Public 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))
이 레슨에는 짧은 퀴즈가 포함되어 있습니다. 레슨을 시작해 문제를 풀고 진행 상황을 기록하세요.
Java 개발자를 위한 Lua의 모든 레슨
직접 연습해 보세요: 온라인 Lua 컴파일러