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
}

newbuttons 将 y、w、h 和纹理设置为默认值,但括号中设置的任何内容都会被覆盖

4

2 回答 2

4

您可以通过将 Doug 的答案与您的原始场景合并来实现您想要的,如下所示:

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
}

...
于 2009-02-06T12:17:22.943 回答
0

如果您将新表的元表设置__index为指向Button它将使用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表中的默认值。

这种技术可用于类或原型面向对象的编程。这里有很多例子。

于 2009-02-06T04:02:26.343 回答