我有一些相对简单的 Lua 代码,它链接到一些 C 和一些 Lua。
local messages = {"Hello World!", "This is some test text", "This is a very long piece of test text with no sense of punctuation or common decency because I want to line wrap okay.", nil}
local i = 1
return {
draw = function()
local blue = zenith.color_rgba(0, 0, 255, 255)
local white = zenith.color_rgba(255, 255, 255, 255)
local red = zenith.color_rgba(255, 0, 0, 255)
local black = zenith.color_rgba(0, 0, 0, 255)
zenith.clear_to_color(black)
if(messages[i]) then
zenith.text_box(white, blue, white, messages[i])
else
zenith.text_box(black, red, white, "+++PINEAPPLE ERROR+++\n+++REDO FROM START+++")
end
end,
event = function(ev)
if(zenith.event_type(ev) == zenith.ev_key_down and
zenith.event_key_code(ev) == "SPACE" and
messages[i] -- don't go off the array end
) then
i = i+1
end
end
}
这正如我所期望的那样工作。当我按空格键时,屏幕上的消息会发生变化,直到它运行到数组的末尾。这些zenith.
方法都是用 C 实现的,使用 Userdata 来存储颜色(我有多种构造颜色的方法(rgba、hsl、命名,所以传递它而不使用数字参数是有意义的)
然后我尝试改变结构,如下所示:
local messages = {"Hello World!", "This is some test text", "This is a very long piece of test text with no sense of punctuation or common decency because I want to line wrap okay.", nil}
local i = 1
local blue = zenith.color_rgba(0, 0, 255, 255)
local white = zenith.color_rgba(255, 255, 255, 255)
local red = zenith.color_rgba(255, 0, 0, 255)
local black = zenith.color_rgba(0, 0, 0, 255)
return {
draw = function()
zenith.clear_to_color(black)
if(messages[i]) then
zenith.text_box(white, blue, white, messages[i])
else
zenith.text_box(black, red, white, "+++PINEAPPLE ERROR+++\n+++REDO FROM START+++")
end
end,
event = function(ev)
if(zenith.event_type(ev) == zenith.ev_key_down and
zenith.event_key_code(ev) == "SPACE" and
messages[i] -- don't go off the array end
) then
i = i+1
end
end
}
唯一的变化是我已将颜色(即用户数据)提取到最外层范围。我希望这能够继续工作,但没有不断分配/收集颜色。相反,我只是得到一个黑屏。有小费吗?我的颜色是否过早地被垃圾收集,因为它们仅在关闭时可用?我还错过了什么其他魔法吗?颜色和颜色之间的唯一区别messages
是它们是用户数据。