“clase Lua” Código de respuesta

clase Lua

MyClass = {foo = "Hello", x = 0} -- Default values
MyClass.__index = MyClass

function MyClass.new(arg)
    local object = {}
    setmetatable(object, SomeClass)
  
  	object.arg = arg
  
    return object
end

function MyClass:bar() -- Be careful, not a '.' but a ':'
  print("World !")
end

function MyClass:addOne()
  self.x = self.x + 1
end

obj1 = MyClass.new("a")
obj2 = MyClass.new("b")

print(obj1.foo) -- Print : Hello
obj2.bar() -- Print : World !

print(ob1.x) -- Print : 0
print(ob2.x) -- Print : 0
obj2:addOne()
print(ob1.x) -- Print : 0
print(ob2.x) -- Print : 1

print(obj1.arg) -- Print : a
print(obj2.arg) -- Print : b
Charlito33

objeto lua

SomeClass = { id = "some_class" }
SomeClass.__index = SomeClass
function SomeClass:Create()
    local this = {}
    setmetatable(this, SomeClass)
    return this
end

c1 = SomeClass:Create()
c2 = SomeClass:Create()

print(c1.id) -- "some_class"
print(c2.id) -- "some_class"
abdullah

clase Lua

-- Classes in lua are just tables.
className = {}

--[[
	className:methodName(parameters) is the intended way to make
	a constructor or a method for the class.
    
    className.methodName(parameters) however,
    is preferred to make static methods.
--]]
function className:new(...)
	self.__index = self
    return setmetatable({...}, self)
end

function className:isInstance(instance)
	return getmetatable(instance) == self
end

c = className:new(1, 2, 3)
print(className:isInstance(c)) -- returns true
ThaCuber

Ejemplo de clase Lua

Car = {}

function Car.new(position, driver, model)
    local newcar = {}

    newcar.Position = position
    newcar.Driver = driver
    newcar.Model = model

    return newcar
end
Benky Lion

Respuestas similares a “clase Lua”

Preguntas similares a “clase Lua”

Explore las respuestas de código populares por idioma

Explorar otros lenguajes de código