Lua 表构造器

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、w、h和纹理的默认值,但是括号中设置的任何内容都会被覆盖。


你不能这样做,你必须使用“点”运算符增加Button表。Button.x = <something> - Luca Matteis
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
}

...

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表中的默认值。

这种技术可用于类或原型面向对象编程。这里有许多示例here


__index周围的括号是多余的。 - David Hanak

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接