• Announcement: Lua.org now officially recommends this forum as a meeting place for the Lua community

How can i get type of class ? (1 Viewer)

qazokmijn01

Newcomer
Joined
Feb 26, 2021
Messages
1
Reaction score
0
function Class(_type,baseClass,init )

local new_class = {}
new_class.mono = {}
if not init and type(baseClass) == 'function' then
init = baseClass
baseClass= nil
elseif type(baseClass) == 'table' then
new_class._type = _type
setmetatable( new_class, { __index = baseClass })
end




local mt = {}
mt.__call = function(class_tbl, ...)
local obj = {}
setmetatable(obj,new_class)
if init then
init(obj,...)
end

return obj

end

new_class.init = init

setmetatable(new_class, mt)

-- Return the super class object of the instance
function new_class:superClass()
return baseClass
end

function new_class:getType()
return _type
end

function new_class:getParentType()
if baseClass == nil then
return _type
else return new_class:superClass():getType()
end
end

local original_type = type
type = function(obj)
return obj:getType()
-- return original_type(obj)
end
new_class.__index = new_class
return new_class
end


Animal = Class("Animal")
Dog = Class("Dog",Animal)
Monster = Class("Monster")

print(type(Animal))

I can't get type of Monster it have an error :
lua: [string "<eval>"]:50: attempt to index local 'obj' (a nil value)
 

dinsdale247

Moderator
Staff member
Community Patron
Creator of WinLua
Joined
Nov 17, 2020
Messages
91
Reaction score
32
Location
Victoria BC
Website
winlua.net
In getParentType, the variable obj just shows up out of nowhere.

I'm not sure why you want to overload the type function in getParentType. I think that's a bad idea. Also your last print statement will just use the Lua type function. Not sure that was your intention?

Indentation is very important in programming and may help with these sorts of problems?

Hope that helps!
 
Top