定义和初始化

类

-- 定义:表就是类
local SomeClass = {}
-- 对象中缺失的字段会到类中查找
SomeClass.__index = SomeClass

function SomeClass:hello()
  return "hello"
end

-- 初始化:类成为新表的元表
local some_class = setmetatable({}, SomeClass)

-- 对象本身没有字段,
-- hello 在类中找到
local is_empty = next(some_class) == nil
-- is_empty = true
local greeting = some_class:hello()
-- greeting = hello

-- 没有类这种类型:对象就是表
local kind = type(some_class)
-- kind = table

print("is_empty = " .. tostring(is_empty))
print("greeting = " .. greeting)
print("kind = " .. kind)