Page 1 of 1
How to make a simple Constructor in lua
Posted: Sun Apr 16, 2017 5:34 pm
by Aconeron
Hi guys, I'm here to ask what I have to do to make a constructor in lua.
I know it's a dumb question but I searched on the Internet and there's nothing that fits well for me.
Also I come from js where things wheren't so difficult
Re: How to make a simple Constructor in lua
Posted: Tue Apr 18, 2017 2:07 am
by Beelz
Bare minimum could be something along the lines of:
Code: Select all
function constructor(x, y)
return {
x = x or math.random()*100,
y = y or math.random()*100
}
end
-- Then create instances
local objects = {}
for i = 1, 10 do
objects[i] = constructor()
print(i, objects[i].x, objects[i].y)
end
Re: How to make a simple Constructor in lua
Posted: Tue Apr 18, 2017 5:34 am
by Davidobot
While what the above poster is certainly a solution, a more elegant one can be achieved with
metatables, and more specifically, the
__index part of metatables.
There is what is called a "prototype". They are exactly what you ate looking for - default values for a table.
EDIT:
Example usage:
Code: Select all
planet = {}
planet.proto = {
x = 0,
y = 0,
r = 15,
m = 1,
t = 0,
hasAtmosphere = true,
speed = 50,
}
planet.mt = {
__index = planet.proto
}
function planet.new(vars)
local set = {}
setmetatable(set, planet.mt)
for k, v in pairs(vars) do
set[k] = v
end
return set
end
This way you can pass only the variables you need to planet.new. Also make sure not to add the sets to the table where the metatable is stored.
Usage:
Code: Select all
local planet1 = planet.new({x = 30, m = 2})
print(planet1.hasAtomosphere) -> true
print(planet1.x) -> 30
print(planet1.speed) -> 50
Re: How to make a simple Constructor in lua
Posted: Tue Apr 18, 2017 6:08 am
by raidho36
I just do it like this.
Code: Select all
local Class = setmetatable ( { }, { __call = function ( class, ... ) return class.new ( ... ) end } )
Class.__index = Class
Class.__call = function ( self ) return Class.new ( self ) end
function Class.new ( other )
local self = setmetatable ( { }, Class )
self.var = other and other.var or 0
return self
end
So if you call class as a function, it produces new instance. And if you call instance as a function, it produces its clone.
Re: How to make a simple Constructor in lua
Posted: Tue Apr 18, 2017 8:25 pm
by Aconeron
Thanks everyone! I didn't excpect some much answers!