Lua Object-Oriented Programming

Lua does not like the object-oriented language which provided class keyword build in language, but Lua can simulate class by using __index metamethod of a table.

Rapid2D’s class function was defined in Rapid2D/samples/test/common/lua/rapid2d/utils.lua.

rd.global.class = function(classname, super)
	local cls

	if type(super) ~= "table" then
		super = nil
	end

	if super then
		cls = {}
		setmetatable(cls, {__index = super})
		cls.super = super
	else
		cls = {ctor = function() return self end}
	end

	cls.__cname = classname
	cls.__index = cls

	function cls.new(...)
		local instance = setmetatable({}, cls)
		instance.class = cls
		return instance:ctor(...)
	end

	return cls
end

Rapid2D closed directly creating global variables, you should use rd.global to create a global variable.

class ONLY support table for the super paramter. If you want to make a base class, reserve super a nil value.

classname is use for tracking, you can get a instance’s class type by below code:

print(instance.class.__cname)