Menu
CoddyTech

可读对象

Coddy 面向 GDScript 开发者的 Lua 课程的第 37 课,共 48 课。

GDScript 对象可以实现 _to_string,以控制 str 生成的文本。Lua 通过对象元表上的 __tostring 元方法提供类似的行为。调用 tostring 时,会将对象作为参数调用该函数。返回一个符合预期格式的字符串,不要在格式化函数内部打印内容。如果运行时会在元表中查找,那么只在实例上定义同名字段是不够的。这些示例会将一个堆栈格式化为标签后跟方括号括起的计数。这样,调用者就能获得可预测的显示文本,而无需暴露引擎实例标识符或 Lua 表的地址。

GDScript 4

extends SceneTree
class Stack:
    var label
    var count
    func _init(item_label, item_count):
        label = item_label
        count = item_count
    func _to_string() -> String:
        return label + "[" + str(count) + "]"
func _init():
    print(str(Stack.new("potion", 3)))
    quit()

Lua 5.1

local Stack = {}
Stack.__index = Stack
function Stack.new(label, count)
  return setmetatable({label = label, count = count}, Stack)
end
function Stack.__tostring(self)
  return self.label .. "[" .. self.count .. "]"
end
print(tostring(Stack.new("potion", 3)))

移植时的陷阱

GDScript 的钩子是 _to_string;Lua 会在元表中查找 __tostring。仅重命名钩子还不够,还必须附加元表。

challenge icon

挑战

简单

实现 Model.new(name, count) 和 Model.__tostring,使其返回 name[count]。输入分为两行,分别是名称和非负整数计数。应用会返回 tostring(instance)。

编辑 app.lua 和 model.lua。可见的锁定文件 main.lua 会从标准输入读取内容并存入行序列,调用 app.run(lines),然后打印其返回值,并在末尾添加一个换行符。不要打印诊断信息,也不要更改模块名称。空输入会生成空序列。所有数值输入都足够小,不会溢出。

公开 API 检查:字符串转换会返回 name[count],包括计数为零的情况;多个实例之间互不影响,重复调用也会得到相同结果。锁定的驱动程序会在调用 app.run 前检查此行为。检查成功时不会打印任何内容。

亲手试试

-- 公共 API 检查
do
local Model=require("model")
local a,b=Model.new("pen",3),Model.new("book",0)
assert(tostring(a)=="pen[3]" and tostring(b)=="book[0]","object text must reflect its own name and count")
assert(tostring(a)=="pen[3]","formatting must be repeatable")
end
local app = require("app")
local lines = {}
for line in io.lines() do lines[#lines + 1] = line end
print(app.run(lines))
quiz icon自我测试

这节课包含一个小测验。开始学习即可作答,并记录你的进度。

面向 GDScript 开发者的 Lua中的所有课

自己练习: Lua 在线编译器