Lua table constructor

how do you make a table by default and then use it when creating other tables?

Example

--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 will get y, w, h and the default texture, but everything in brackets will be overwritten

+4
source share
2 answers

You can achieve what you want by combining Doug's answer with the source script, for example:

 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 } 

(I really tested this, it works.)

Change You can make it a little prettier and reuse it like this:

 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 } ... 
+4
source

If you set up a new metatetered __index table to point to a Button , it will use the default values ​​from the Button table.

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

Now, when you make buttons with newButton() , they use the default values ​​from the Button table.

This method can be used for object-oriented programming of classes or prototypes. There are many examples here .

0
source

All Articles