我有一些相对简单的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,named,因此有必要将其传递而不使用数字参数)
然后我尝试更改结构,就像这样:
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
之间的唯一区别是它们是Userdata。
答案 0 :(得分:1)
解决了!在初始化显示之前,将调用外部作用域。这会导致颜色创建代码返回一个全部设置为0的颜色对象(因为很明显,我们无法在显示初始化之前创建颜色,这很合理(!))。