【Lua】题目小练6
题目一:基础类封装
要求:
请用 Lua 实现一个 Person 类,具备以下功能:
拥有属性:name 和 age
拥有方法:sayHello(),输出 "Hello, I am <name>, <age> years old."
使用 Person.new(name, age) 创建对象
local Person = {} Person.__index = Personfunction Person:new()local tb = {name = "MyName",age = "MyAge"}setmetatable(tb, self)return tb endfunction Person:sayHello()print("Hello, I am "..self.name..", "..self.age.." years old.") endlocal t = Person:new() t.name = "阿T" t.age = 16 t:sayHello()
-- 题目二:封装一个类支持默认值和检查
请你写一个 Animal 类:
属性有:name, type, age(默认 0)
new(name, type, age) 构造方法
如果 age 小于 0,强制置为 0
方法:
describe():输出 "<name> is a <type>, <age> years old."
local Animal = {} Animal.__index = Animalfunction Animal:new(name, type, age)local obj = {name = name,type = type,age = (age and age > 0) and age or 0}setmetatable(obj, Animal)return obj endfunction Animal:describe()print(self.name.." is a "..self.type..", "..self.age.." years old.") endlocal t = Animal:new("Hello","cat",-1) t:describe()
----------逻辑运算符题目----------
-- a and b
-- a为true 返回b
-- a为false,返回a
-- a or b
-- --a为true,返回a
-- --a为false,返回b
print(false and "hello") --> falseprint("hi" and "hello") --> helloprint(nil or 123) --> 123print(0 or "default") --> 0print(false or nil) --> nil
-- 如果 age >= 18 就返回 "adult",否则返回 "child"local age = 20local result = (age >= 18) and "adult" or "child"print(result) --> adult-- 试试 age = 0 呢?age = 0result = (age >= 18) and "adult" or "child"print(result) --> child
function check(val)return val and "OK" or "BAD" endprint(check(true)) --> OKprint(check(false)) --> BADprint(check("yes")) --> OKprint(check(nil)) --> BADprint(check(0)) --> OK