문자열에서 흥미로운 속성을 추출하기 위해 문자열에서 작동하는 많은 함수가 있습니다. 이러한 기능의 많은에 의해 호출되는 하나 개의 특정 기능은 매우 비싼 궁극적 값의 테이블을 생성 비싼 함수가 테이블을 돌려 정확히 한 번만 스트링 당 테이블을 생성하도록루아에서 개별 함수 호출 사이의 문자열에 비싼 테이블 계산 캐싱
local function expensive(s)
local t = nil
return function()
if not t then
t = {}
-- some expensive operations with s which add items to t
end
return t
end
end
local function fn1(s)
local t = expensive(s)
-- some other fast operations using t and s
end
local function fn2(s)
local t = expensive(s)
-- some other fast operations using t and s
end
local s1, s2 = 'a', 'b'
fn1(s1) -- should create the 't' table for s1
fn1(s2) -- should create the 't' table for s2
fn2(s1) -- should not create the 't' table again for s1
fn1(s2) -- should also not create the 't' table again for s2
가 어떻게 그것을 만들 수 있습니다 두 경우 모두? 차라리 테이블을 지구 환경에 노출시키지 않을 것입니다. 이것은 클로저의 영리한 사용에 의해 달성 될 수 있다고 생각하지만 구조를 충분히 잘 모른다.
do ... end 블록은 영리합니다! 그것들은 lua 레퍼런스 매뉴얼에서 비슷한 예제를 가지고 있지만이 경우에는 사용하지 않을 생각이다. – ruser9575ba6f