【游戏】
一、规则机制
线上事故:聊天窗口没有输入历史,玩家反复打同样的话组队喊话,加了历史又出现上下键在光标位置乱跳的怪象。输入历史立三条规矩:回车发送时非空发言压入历史栈,重复的相邻发言不重复入栈;上键从栈顶向旧翻,下键向新翻,翻过头顶回当前草稿;翻出的历史项可直接修改发送,发送后按新发言入栈。历史上限五十条,超出挤掉最旧的。
二、错误写法
-- 错误:上下键直接回填不记游标,来回乱跳
function onUp()
input:setText(history[hIdx])
end
function onDown()
input:setText(history[hIdx + 1])
end
三、正确写法
local history, hIdx = {}, 0
local draft = ""
local function onSend(text)
if text == "" then return end
if history[#history] ~= text then
history[#history + 1] = text
if #history > 50 then
table.remove(history, 1)
end
end
hIdx = #history + 1
end
local function onUp()
if hIdx > 1 then
if hIdx > #history then draft = input:getText() end
hIdx = hIdx - 1
input:setText(history[hIdx])
end
end
local function onDown()
if hIdx < #history then
hIdx = hIdx + 1
input:setText(history[hIdx])
elseif hIdx == #history then
hIdx = hIdx + 1
input:setText(draft)
end
end
四、边界处理
相邻重复发言不入栈;上翻首条后不再向上;下翻越过栈顶回到发送前草稿;历史上限五十条。
五、FAQ
问:翻出的历史能改吗?
答:能,修改后发送按新内容入栈。
问:草稿会丢吗?
答:上翻前自动留存草稿,下翻到头即回草稿。
全站技术干货持续更新:996 引擎 / Lua 实战帖,语法、参数与示例一篇讲透。进入文章地图 · 查看全部 →
【语法算法】 元方法 __len 的触发就这一行: 对带 __len 的表做 t 操作时,Lua 调用 __len 而不是返…
【语法算法】 load 的编译本质就这一行: load 把字符串编译成函数——字符串里的代码被编译成可调用的函数——调用返回…
【语法算法】 error 的传播本质就这一行: error 抛出一个错误——第二个参数指定错误信息的层级——层级 2 表示把…
【语法算法】 pcall 的保护调用本质就这两行: pcall 把函数包在保护壳里执行——函数内部报错不会传播到外层——ok…
【语法算法】 元方法 __tostring 的触发就这一行: 对带 __tostring 的表做 tostring(t) 或…
【语法算法】 元方法 __call 的触发就这一行: 对带 __call 元方法的表做函数调用 t(...) 时,Lua 不…