2009-02-06 5 views
4

기본 테이블을 만들고 다른 테이블을 만들 때 어떻게 사용합니까?루아 테이블 생성자

예를

--default table 
Button = { 
x = 0, 
y = 0, 
w = 10, 
h = 10, 
Texture = "buttonimg.png", 
onClick = function() end 
} 

newbutton = Button { 
onClick = function() 
    print("button 1 pressed") 
end 
} 


newbutton2 = Button { 
x = 12, 
onClick = function() 
    print("button 2 pressed") 
end 
} 
y를 얻을 괄호에 설정된 값 아무것도하지만, 기본 설정, 시간과 질감 승 얻을 것이다

newbuttons 덮어

+0

당신은 할 수 없습니다. "도트"연산자로 Button 테이블을 보강해야합니다. Button.x =

답변

4

당신은 다음과 같이 원래 시나리오 더그의 답변을 병합하여 원하는 것을 얻을 수 있습니다. (나는 실제로 작동이 테스트)

Button = { 
    x = 0, 
    y = 0, 
    w = 10, 
    h = 10, 
    Texture = "buttonimg.png", 
    onClick = function() end 
} 
setmetatable(Button, 
     { __call = function(self, init) 
         return setmetatable(init or {}, { __index = Button }) 
        end }) 

newbutton = Button { 
    onClick = function() 
       print("button 1 pressed") 
      end 
} 

newbutton2 = Button { 
    x = 12, 
    onClick = function() 
       print("button 2 pressed") 
      end 
} 

편집 : 당신은 할 수 있습니다 이것은 조금 더 예민하고 재사용이 가능합니다 :

function prototype(class) 
    return setmetatable(class, 
      { __call = function(self, init) 
          return setmetatable(init or {}, 
               { __index = class }) 
         end }) 
end 

Button = prototype { 
    x = 0, 
    y = 0, 
    w = 10, 
    h = 10, 
    Texture = "buttonimg.png", 
    onClick = function() end 
} 

... 
0

새 테이블의 메타 테이블의 __indexButton를 가리 키도록 설정하면 Button 테이블의 기본값을 사용합니다.

--default table 
Button = { 
x = 0, 
y = 0, 
w = 10, 
h = 10, 
Texture = "buttonimg.png", 
onClick = function() end 
} 

function newButton() return setmetatable({},{__index=Button}) end 

이제 newButton()와 버튼들이 Button 테이블에서 기본값을 사용 할 때.

이 기술은 클래스 또는 프로토 타입 객체 지향 프로그래밍에 사용할 수 있습니다. 많은 예가 here입니다.

+0

__index 주위의 대괄호는 불필요합니다. –

+0

감사합니다, David; 내 껍질에서 잘못된 텍스트를 복사했습니다. 결정된. –