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
How to make a simple Constructor in lua
Forum rules
Before you make a thread asking for help, read this.
Before you make a thread asking for help, read this.
Re: How to make a simple Constructor in lua
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
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:
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:
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
Usage:
Code: Select all
local planet1 = planet.new({x = 30, m = 2})
print(planet1.hasAtomosphere) -> true
print(planet1.x) -> 30
print(planet1.speed) -> 50
PM me on here or elsewhere if you'd like to discuss porting your game to Nintendo Switch via mazette!
personal page and a raycaster
personal page and a raycaster
Re: How to make a simple Constructor in lua
I just do it like this.
So if you call class as a function, it produces new instance. And if you call instance as a function, it produces its clone.
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
Re: How to make a simple Constructor in lua
Thanks everyone! I didn't excpect some much answers!
Who is online
Users browsing this forum: Bing [Bot], Google [Bot], Semrush [Bot] and 3 guests